diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index ee90d788591..ccd2e40fce0 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -41,8 +41,8 @@ Provide any additional context that may be helpful in understanding and/or resol Please add X in at least one of the boxes as appropriate. In order for an issue to be accepted, a developer needs to be able to reproduce the issue on a currently supported version. If you are looking for a workaround for an issue with an older version, please visit the forums at https://dnncommunity.org/forums --> * [ ] 10.00.00 alpha build -* [ ] 09.07.00 release candidate -* [ ] 09.06.02 latest supported release +* [ ] 09.07.01 release candidate +* [ ] 09.07.00 latest supported release ## Affected browser - \ No newline at end of file + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs index 01f104f9c10..e81b717b324 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs @@ -2,241 +2,244 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Content -{ - using System; +namespace DotNetNuke.Tests.Content +{ + using System; using System.Linq; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Content.Data; - using DotNetNuke.Entities.Content.Taxonomy; - using DotNetNuke.Services.Cache; - using DotNetNuke.Tests.Content.Mocks; - using DotNetNuke.Tests.Utilities; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; using DotNetNuke.Tests.Utilities.Mocks; using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using NUnit.Framework; - - /// - /// Summary description for ScopeTypeTests. - /// - [TestFixture] - public class ScopeTypeControllerTests - { - private Mock mockCache; - - [SetUp] - public void SetUp() - { + + using Moq; + + using NUnit.Framework; + + /// + /// Summary description for ScopeTypeTests. + /// + [TestFixture] + public class ScopeTypeControllerTests + { + private Mock mockCache; + + [SetUp] + public void SetUp() + { var serviceCollection = new ServiceCollection(); serviceCollection.AddTransient(container => Mock.Of()); serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - // Register MockCachingProvider - this.mockCache = MockComponentProvider.CreateNew(); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); - } - - [TearDown] - public void TearDown() - { - Globals.DependencyProvider = null; - MockComponentProvider.ResetContainer(); - } - - [Test] - public void ScopeTypeController_AddScopeType_Throws_On_Null_ScopeType() - { - // Arrange - var mockDataService = new Mock(); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => scopeTypeController.AddScopeType(null)); - } - - [Test] - public void ScopeTypeController_AddScopeType_Calls_DataService_On_Valid_Arguments() - { - // Arrange - var mockDataService = new Mock(); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - var scopeType = ContentTestHelper.CreateValidScopeType(); - - // Act - int scopeTypeId = scopeTypeController.AddScopeType(scopeType); - - // Assert - mockDataService.Verify(ds => ds.AddScopeType(scopeType)); - } - - [Test] - public void ScopeTypeController_AddScopeType_Returns_ValidId_On_Valid_ScopeType() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.AddScopeType(It.IsAny())).Returns(Constants.SCOPETYPE_AddScopeTypeId); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); - - // Act - int scopeTypeId = scopeTypeController.AddScopeType(scopeType); - - // Assert - Assert.AreEqual(Constants.SCOPETYPE_AddScopeTypeId, scopeTypeId); - } - - [Test] - public void ScopeTypeController_AddScopeType_Sets_ValidId_On_Valid_ScopeType() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.AddScopeType(It.IsAny())).Returns(Constants.SCOPETYPE_AddScopeTypeId); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - var scopeType = ContentTestHelper.CreateValidScopeType(); - - // Act - scopeTypeController.AddScopeType(scopeType); - - // Assert - Assert.AreEqual(Constants.SCOPETYPE_AddScopeTypeId, scopeType.ScopeTypeId); - } - - [Test] - public void ScopeTypeController_DeleteScopeType_Throws_On_Null_ScopeType() - { - // Arrange - var mockDataService = new Mock(); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => scopeTypeController.DeleteScopeType(null)); - } - - [Test] - public void ScopeTypeController_DeleteScopeType_Throws_On_Negative_ScopeTypeId() - { - // Arrange - var mockDataService = new Mock(); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); - scopeType.ScopeTypeId = Null.NullInteger; - - Assert.Throws(() => scopeTypeController.DeleteScopeType(scopeType)); - } - - [Test] - public void ScopeTypeController_DeleteScopeType_Calls_DataService_On_Valid_ContentTypeId() - { - // Arrange - var mockDataService = new Mock(); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - var scopeType = ContentTestHelper.CreateValidScopeType(); - scopeType.ScopeTypeId = Constants.SCOPETYPE_ValidScopeTypeId; - - // Act - scopeTypeController.DeleteScopeType(scopeType); - - // Assert - mockDataService.Verify(ds => ds.DeleteScopeType(scopeType)); - } - - [Test] - public void ScopeTypeController_GetScopeTypes_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateValidScopeTypesReader(Constants.SCOPETYPE_ValidScopeTypeCount)); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - // Act - IQueryable scopeTypes = scopeTypeController.GetScopeTypes(); - - // Assert - mockDataService.Verify(ds => ds.GetScopeTypes()); - } - - [Test] - public void ScopeTypeController_GetScopeTypes_Returns_Empty_List_Of_ScopeTypes_If_No_ScopeTypes() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateEmptyScopeTypeReader()); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - // Act - var scopeTypes = scopeTypeController.GetScopeTypes(); - - // Assert - Assert.IsNotNull(scopeTypes); - Assert.AreEqual(0, scopeTypes.Count()); - } - - [Test] - public void ScopeTypeController_GetScopeTypes_Returns_List_Of_ScopeTypes() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateValidScopeTypesReader(Constants.SCOPETYPE_ValidScopeTypeCount)); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - // Act - var scopeTypes = scopeTypeController.GetScopeTypes(); - - // Assert - Assert.AreEqual(Constants.SCOPETYPE_ValidScopeTypeCount, scopeTypes.Count()); - } - - [Test] - public void ScopeTypeController_UpdateScopeType_Throws_On_Null_ScopeType() - { - // Arrange - var mockDataService = new Mock(); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => scopeTypeController.UpdateScopeType(null)); - } - - [Test] - public void ScopeTypeController_UpdateScopeType_Throws_On_Negative_ScopeTypeId() - { - // Arrange - var mockDataService = new Mock(); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); - scopeType.ScopeType = Constants.SCOPETYPE_InValidScopeType; - - Assert.Throws(() => scopeTypeController.UpdateScopeType(scopeType)); - } - - [Test] - public void ScopeTypeController_UpdateScopeType_Calls_DataService_On_Valid_ContentType() - { - // Arrange - var mockDataService = new Mock(); - var scopeTypeController = new ScopeTypeController(mockDataService.Object); - - ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); - scopeType.ScopeTypeId = Constants.SCOPETYPE_UpdateScopeTypeId; - scopeType.ScopeType = Constants.SCOPETYPE_UpdateScopeType; - - // Act - scopeTypeController.UpdateScopeType(scopeType); - - // Assert - mockDataService.Verify(ds => ds.UpdateScopeType(scopeType)); - } - } -} + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + // Register MockCachingProvider + this.mockCache = MockComponentProvider.CreateNew(); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + MockComponentProvider.ResetContainer(); + } + + [Test] + public void ScopeTypeController_AddScopeType_Throws_On_Null_ScopeType() + { + // Arrange + var mockDataService = new Mock(); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => scopeTypeController.AddScopeType(null)); + } + + [Test] + public void ScopeTypeController_AddScopeType_Calls_DataService_On_Valid_Arguments() + { + // Arrange + var mockDataService = new Mock(); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + var scopeType = ContentTestHelper.CreateValidScopeType(); + + // Act + int scopeTypeId = scopeTypeController.AddScopeType(scopeType); + + // Assert + mockDataService.Verify(ds => ds.AddScopeType(scopeType)); + } + + [Test] + public void ScopeTypeController_AddScopeType_Returns_ValidId_On_Valid_ScopeType() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.AddScopeType(It.IsAny())).Returns(Constants.SCOPETYPE_AddScopeTypeId); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); + + // Act + int scopeTypeId = scopeTypeController.AddScopeType(scopeType); + + // Assert + Assert.AreEqual(Constants.SCOPETYPE_AddScopeTypeId, scopeTypeId); + } + + [Test] + public void ScopeTypeController_AddScopeType_Sets_ValidId_On_Valid_ScopeType() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.AddScopeType(It.IsAny())).Returns(Constants.SCOPETYPE_AddScopeTypeId); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + var scopeType = ContentTestHelper.CreateValidScopeType(); + + // Act + scopeTypeController.AddScopeType(scopeType); + + // Assert + Assert.AreEqual(Constants.SCOPETYPE_AddScopeTypeId, scopeType.ScopeTypeId); + } + + [Test] + public void ScopeTypeController_DeleteScopeType_Throws_On_Null_ScopeType() + { + // Arrange + var mockDataService = new Mock(); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => scopeTypeController.DeleteScopeType(null)); + } + + [Test] + public void ScopeTypeController_DeleteScopeType_Throws_On_Negative_ScopeTypeId() + { + // Arrange + var mockDataService = new Mock(); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); + scopeType.ScopeTypeId = Null.NullInteger; + + Assert.Throws(() => scopeTypeController.DeleteScopeType(scopeType)); + } + + [Test] + public void ScopeTypeController_DeleteScopeType_Calls_DataService_On_Valid_ContentTypeId() + { + // Arrange + var mockDataService = new Mock(); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + var scopeType = ContentTestHelper.CreateValidScopeType(); + scopeType.ScopeTypeId = Constants.SCOPETYPE_ValidScopeTypeId; + + // Act + scopeTypeController.DeleteScopeType(scopeType); + + // Assert + mockDataService.Verify(ds => ds.DeleteScopeType(scopeType)); + } + + [Test] + public void ScopeTypeController_GetScopeTypes_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateValidScopeTypesReader(Constants.SCOPETYPE_ValidScopeTypeCount)); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + // Act + IQueryable scopeTypes = scopeTypeController.GetScopeTypes(); + + // Assert + mockDataService.Verify(ds => ds.GetScopeTypes()); + } + + [Test] + public void ScopeTypeController_GetScopeTypes_Returns_Empty_List_Of_ScopeTypes_If_No_ScopeTypes() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateEmptyScopeTypeReader()); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + // Act + var scopeTypes = scopeTypeController.GetScopeTypes(); + + // Assert + Assert.IsNotNull(scopeTypes); + Assert.AreEqual(0, scopeTypes.Count()); + } + + [Test] + public void ScopeTypeController_GetScopeTypes_Returns_List_Of_ScopeTypes() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateValidScopeTypesReader(Constants.SCOPETYPE_ValidScopeTypeCount)); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + // Act + var scopeTypes = scopeTypeController.GetScopeTypes(); + + // Assert + Assert.AreEqual(Constants.SCOPETYPE_ValidScopeTypeCount, scopeTypes.Count()); + } + + [Test] + public void ScopeTypeController_UpdateScopeType_Throws_On_Null_ScopeType() + { + // Arrange + var mockDataService = new Mock(); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => scopeTypeController.UpdateScopeType(null)); + } + + [Test] + public void ScopeTypeController_UpdateScopeType_Throws_On_Negative_ScopeTypeId() + { + // Arrange + var mockDataService = new Mock(); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); + scopeType.ScopeType = Constants.SCOPETYPE_InValidScopeType; + + Assert.Throws(() => scopeTypeController.UpdateScopeType(scopeType)); + } + + [Test] + public void ScopeTypeController_UpdateScopeType_Calls_DataService_On_Valid_ContentType() + { + // Arrange + var mockDataService = new Mock(); + var scopeTypeController = new ScopeTypeController(mockDataService.Object); + + ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); + scopeType.ScopeTypeId = Constants.SCOPETYPE_UpdateScopeTypeId; + scopeType.ScopeType = Constants.SCOPETYPE_UpdateScopeType; + + // Act + scopeTypeController.UpdateScopeType(scopeType); + + // Assert + mockDataService.Verify(ds => ds.UpdateScopeType(scopeType)); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs index 0aeb25a7cd9..0b45b390503 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs @@ -2,626 +2,629 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Content -{ - using System; +namespace DotNetNuke.Tests.Content +{ + using System; using System.Linq; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Content; - using DotNetNuke.Entities.Content.Data; - using DotNetNuke.Entities.Content.Taxonomy; - using DotNetNuke.Entities.Users; - using DotNetNuke.Services.Cache; - using DotNetNuke.Tests.Content.Mocks; - using DotNetNuke.Tests.Utilities; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; using DotNetNuke.Tests.Utilities.Mocks; using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using NUnit.Framework; - - /// - /// Summary description for TermTests. - /// - [TestFixture] - public class TermControllerTests - { - private Mock mockCache; - - [SetUp] - public void SetUp() - { + + using Moq; + + using NUnit.Framework; + + /// + /// Summary description for TermTests. + /// + [TestFixture] + public class TermControllerTests + { + private Mock mockCache; + + [SetUp] + public void SetUp() + { var serviceCollection = new ServiceCollection(); serviceCollection.AddTransient(container => Mock.Of()); serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - Mock vocabularyController = MockHelper.CreateMockVocabularyController(); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); - - // Register MockCachingProvider - this.mockCache = MockComponentProvider.CreateNew(); - } - - [TearDown] - public void TearDown() - { - Globals.DependencyProvider = null; - MockComponentProvider.ResetContainer(); - } - - [Test] - public void TermController_AddTerm_Throws_On_Null_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => termController.AddTerm(null)); - } - - [Test] - public void TermController_AddTerm_Throws_On_Invalid_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - term.Name = Constants.TERM_InValidName; - - // Act, Arrange - Assert.Throws(() => termController.AddTerm(term)); - } - - [Test] - public void TermController_AddTerm_Throws_On_Negative_VocabularyId() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); - - // Act, Arrange - Assert.Throws(() => termController.AddTerm(term)); - } - - [Test] - public void TermController_AddTerm_Should_Call_DataService_AddSimpleTerm_If_Term_Is_Simple_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - - // Act - int termId = termController.AddTerm(term); - - // Assert - mockDataService.Verify(ds => ds.AddSimpleTerm(term, UserController.Instance.GetCurrentUserInfo().UserID)); - } - - [Test] - public void TermController_AddTerm_Should_Call_DataService_AddHeirarchicalTerm_If_Term_Is_Heirarchical_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); - - // Act - int termId = termController.AddTerm(term); - - // Assert - mockDataService.Verify(ds => ds.AddHeirarchicalTerm(term, UserController.Instance.GetCurrentUserInfo().UserID)); - } - - [Test] - public void TermController_AddTerm_Returns_Valid_Id_On_Valid_Term_If_Term_Is_Simple_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - mockDataService.Setup(ds => ds.AddSimpleTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - - // Act - int termId = termController.AddTerm(term); - - // Assert - Assert.AreEqual(Constants.TERM_AddTermId, termId); - } - - [Test] - public void TermController_AddTerm_Sets_Valid_Id_On_Valid_Term_If_Term_Is_Simple_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - mockDataService.Setup(ds => ds.AddSimpleTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - - // Act - termController.AddTerm(term); - - // Assert - Assert.AreEqual(Constants.TERM_AddTermId, term.TermId); - } - - [Test] - public void TermController_AddTerm_Returns_Valid_Id_On_Valid_Term_If_Term_Is_Heirarchical_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - mockDataService.Setup(ds => ds.AddHeirarchicalTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); - - Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); - - // Act - int termId = termController.AddTerm(term); - - // Assert - Assert.AreEqual(Constants.TERM_AddTermId, termId); - } - - [Test] - public void TermController_AddTerm_Sets_Valid_Id_On_Valid_Term_If_Term_Is_Heirarchical_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - mockDataService.Setup(ds => ds.AddHeirarchicalTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); - - Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); - - // Act - termController.AddTerm(term); - - // Assert - Assert.AreEqual(Constants.TERM_AddTermId, term.TermId); - } - - [Test] - public void TermController_AddTerm_Clears_Term_Cache_On_Valid_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - - // Act - termController.AddTerm(term); - - // Assert - this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } - - [Test] - public void TermController_AddTermToContent_Throws_On_Null_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - ContentItem content = ContentTestHelper.CreateValidContentItem(); - - // Act, Arrange - Assert.Throws(() => termController.AddTermToContent(null, content)); - } - - [Test] - public void TermController_AddTermToContent_Throws_On_Null_ContentItem() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - - // Act, Arrange - Assert.Throws(() => termController.AddTermToContent(term, null)); - } - - [Test] - public void TermController_AddTermToContent_Should_Call_DataService_If_Valid_Params() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - ContentItem content = ContentTestHelper.CreateValidContentItem(); - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - - // Act - termController.AddTermToContent(term, content); - - // Assert - mockDataService.Verify(ds => ds.AddTermToContent(term, content)); - } - - [Test] - public void TermController_DeleteTerm_Throws_On_Null_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => termController.DeleteTerm(null)); - } - - [Test] - public void TermController_DeleteTerm_Throws_On_Negative_TermId() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - var term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - term.TermId = Null.NullInteger; - - // Act, Arrange - Assert.Throws(() => termController.DeleteTerm(term)); - } - - [Test] - public void TermController_DeleteTerm_Should_Call_DataService_DeleteSimpleTerm_If_Term_Is_Simple_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - var term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - term.TermId = Constants.TERM_DeleteTermId; - - // Act - termController.DeleteTerm(term); - - // Assert - mockDataService.Verify(ds => ds.DeleteSimpleTerm(term)); - } - - [Test] - public void TermController_DeleteTerm_Should_Call_DataService_DeleteHeirarchicalTerm_If_Term_Is_Heirarchical_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - var term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); - term.TermId = Constants.TERM_DeleteTermId; - - // Act - termController.DeleteTerm(term); - - // Assert - mockDataService.Verify(ds => ds.DeleteHeirarchicalTerm(term)); - } - - [Test] - public void TermController_DeleteTerm_Clears_Term_Cache_On_Valid_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - var term = new Term(Constants.VOCABULARY_ValidVocabularyId) { TermId = Constants.TERM_DeleteTermId }; - - // Act - termController.DeleteTerm(term); - - // Assert - this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } - - [Test] - public void TermController_GetTerm_Throws_On_Negative_TermId() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => termController.GetTerm(Null.NullInteger)); - } - - [Test] - public void TermController_GetTerm_Returns_Null_On_InValidTermId() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_InValidTermId)).Returns(MockHelper.CreateEmptyTermReader()); - - var termController = new TermController(mockDataService.Object); - - // Act - Term term = termController.GetTerm(Constants.TERM_InValidTermId); - - // Assert - Assert.IsNull(term); - } - - [Test] - public void TermController_GetTerm_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_ValidTermId)).Returns(MockHelper.CreateValidTermReader()); - var termController = new TermController(mockDataService.Object); - - // Act - Term term = termController.GetTerm(Constants.TERM_ValidTermId); - - // Assert - mockDataService.Verify(ds => ds.GetTerm(Constants.TERM_ValidTermId)); - } - - [Test] - public void TermController_GetTerm_Returns_Term_On_Valid_TermId() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_ValidTermId)).Returns(MockHelper.CreateValidTermReader()); - - var termController = new TermController(mockDataService.Object); - - // Act - var term = termController.GetTerm(Constants.TERM_ValidTermId); - - // Assert - Assert.AreEqual(Constants.TERM_ValidTermId, term.TermId); - Assert.AreEqual(Constants.TERM_ValidName, term.Name); - } - - [Test] - public void TermController_GetTermsByContent_Throws_On_Invalid_ContentItemId() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => termController.GetTermsByContent(Null.NullInteger)); - } - - [Test] - public void TermController_GetTermsByContent_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( - Constants.TERM_ValidCountForContent1, - v => Constants.TERM_ValidVocabularyId, - c => Constants.TERM_ValidContent1)); - var termController = new TermController(mockDataService.Object); - - // Act - IQueryable terms = termController.GetTermsByContent(Constants.TERM_ValidContent1); - - // Assert - mockDataService.Verify(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)); - } - - [Test] - public void TermController_GetTermsByContent_Returns_Terms_On_Valid_ContentItemId() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( - Constants.TERM_ValidCountForContent1, - v => Constants.TERM_ValidVocabularyId, - c => Constants.TERM_ValidContent1)); - - var termController = new TermController(mockDataService.Object); - - // Act - var terms = termController.GetTermsByContent(Constants.TERM_ValidContent1).ToList(); - - // Assert - Assert.AreEqual(Constants.TERM_ValidCountForContent1, terms.Count); - - for (int i = 0; i < Constants.TERM_ValidCountForContent1; i++) - { - Assert.AreEqual(i + Constants.TERM_ValidTermId, terms[i].TermId); - Assert.AreEqual(ContentTestHelper.GetTermName(i + Constants.TERM_ValidTermId), terms[i].Name); - } - } - - [Test] - public void TermController_GetTermsByVocabulary_Throws_On_Invalid_VocabularyId() - { - // Arrange - var mockDataService = new Mock(); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); - var termController = new TermController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => termController.GetTermsByVocabulary(Null.NullInteger)); - } - - [Test] - public void TermController_GetTermsByVocabulary_Returns_Terms_On_Valid_VocabularyId() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1)).Returns(MockHelper.CreateValidTermsReader( - Constants.TERM_ValidCountForVocabulary1, - v => Constants.TERM_ValidVocabulary1, - c => Constants.TERM_ValidContent1)); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); - - var termController = new TermController(mockDataService.Object); - - // Act - var terms = termController.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1).ToList(); - - // Assert - Assert.AreEqual(Constants.TERM_ValidCountForVocabulary1, terms.Count); - - for (int i = 0; i < Constants.TERM_ValidCountForVocabulary1; i++) - { - Assert.AreEqual(i + Constants.TERM_ValidTermId, terms[i].TermId); - Assert.AreEqual(ContentTestHelper.GetTermName(i + Constants.TERM_ValidTermId), terms[i].Name); - } - } - - [Test] - public void TermController_GetTermsByVocabulary_Throws_On_Invalid_VocabularyName() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => termController.GetTermsByVocabulary(Null.NullString)); - } - - [Test] - public void TermController_RemoveTermsFromContent_Throws_On_Null_ContentItem() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => termController.RemoveTermsFromContent(null)); - } - - [Test] - public void TermController_RemoveTermsFromContent_Should_Call_DataService_If_Valid_Params() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - ContentItem content = ContentTestHelper.CreateValidContentItem(); - - // Act - termController.RemoveTermsFromContent(content); - - // Assert - mockDataService.Verify(ds => ds.RemoveTermsFromContent(content)); - } - - [Test] - public void TermController_UpdateTerm_Throws_On_Null_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => termController.UpdateTerm(null)); - } - - [Test] - public void TermController_UpdateTerm_Throws_On_Negative_TermId() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); - - // Act, Arrange - Assert.Throws(() => termController.UpdateTerm(term)); - } - - [Test] - public void TermController_UpdateTerm_Throws_On_Invalid_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - term.Name = Constants.TERM_InValidName; - - // Act, Arrange - Assert.Throws(() => termController.UpdateTerm(term)); - } - - [Test] - public void TermController_UpdateTerm_Throws_On_Negative_VocabularyId() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); - - // Act, Arrange - Assert.Throws(() => termController.UpdateTerm(term)); - } - - [Test] - public void TermController_UpdateTerm_Should_Call_DataService_UpdateSimpleTerm_If_Term_Is_Simple_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - term.TermId = Constants.TERM_UpdateTermId; - term.Name = Constants.TERM_UpdateName; - term.Weight = Constants.TERM_UpdateWeight; - - // Act - termController.UpdateTerm(term); - - // Assert - mockDataService.Verify(ds => ds.UpdateSimpleTerm(term, UserController.Instance.GetCurrentUserInfo().UserID)); - } - - [Test] - public void TermController_UpdateTerm_Should_Call_DataService_UpdateHeirarchicalTerm_If_Term_Is_Heirarchical_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); - term.TermId = Constants.TERM_UpdateTermId; - term.Name = Constants.TERM_UpdateName; - term.Weight = Constants.TERM_UpdateWeight; - - // Act - termController.UpdateTerm(term); - - // Assert - mockDataService.Verify(ds => ds.UpdateHeirarchicalTerm(term, UserController.Instance.GetCurrentUserInfo().UserID)); - } - - [Test] - public void TermController_UpdateTerm_Clears_Term_Cache_On_Valid_Term() - { - // Arrange - var mockDataService = new Mock(); - var termController = new TermController(mockDataService.Object); - - Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - term.TermId = Constants.TERM_UpdateTermId; - term.Name = Constants.TERM_UpdateName; - term.Weight = Constants.TERM_UpdateWeight; - - // Act - termController.UpdateTerm(term); - - // Assert - this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } - } -} + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + Mock vocabularyController = MockHelper.CreateMockVocabularyController(); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); + + // Register MockCachingProvider + this.mockCache = MockComponentProvider.CreateNew(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + MockComponentProvider.ResetContainer(); + } + + [Test] + public void TermController_AddTerm_Throws_On_Null_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => termController.AddTerm(null)); + } + + [Test] + public void TermController_AddTerm_Throws_On_Invalid_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + term.Name = Constants.TERM_InValidName; + + // Act, Arrange + Assert.Throws(() => termController.AddTerm(term)); + } + + [Test] + public void TermController_AddTerm_Throws_On_Negative_VocabularyId() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); + + // Act, Arrange + Assert.Throws(() => termController.AddTerm(term)); + } + + [Test] + public void TermController_AddTerm_Should_Call_DataService_AddSimpleTerm_If_Term_Is_Simple_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + + // Act + int termId = termController.AddTerm(term); + + // Assert + mockDataService.Verify(ds => ds.AddSimpleTerm(term, UserController.Instance.GetCurrentUserInfo().UserID)); + } + + [Test] + public void TermController_AddTerm_Should_Call_DataService_AddHeirarchicalTerm_If_Term_Is_Heirarchical_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); + + // Act + int termId = termController.AddTerm(term); + + // Assert + mockDataService.Verify(ds => ds.AddHeirarchicalTerm(term, UserController.Instance.GetCurrentUserInfo().UserID)); + } + + [Test] + public void TermController_AddTerm_Returns_Valid_Id_On_Valid_Term_If_Term_Is_Simple_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + mockDataService.Setup(ds => ds.AddSimpleTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + + // Act + int termId = termController.AddTerm(term); + + // Assert + Assert.AreEqual(Constants.TERM_AddTermId, termId); + } + + [Test] + public void TermController_AddTerm_Sets_Valid_Id_On_Valid_Term_If_Term_Is_Simple_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + mockDataService.Setup(ds => ds.AddSimpleTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + + // Act + termController.AddTerm(term); + + // Assert + Assert.AreEqual(Constants.TERM_AddTermId, term.TermId); + } + + [Test] + public void TermController_AddTerm_Returns_Valid_Id_On_Valid_Term_If_Term_Is_Heirarchical_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + mockDataService.Setup(ds => ds.AddHeirarchicalTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); + + Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); + + // Act + int termId = termController.AddTerm(term); + + // Assert + Assert.AreEqual(Constants.TERM_AddTermId, termId); + } + + [Test] + public void TermController_AddTerm_Sets_Valid_Id_On_Valid_Term_If_Term_Is_Heirarchical_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + mockDataService.Setup(ds => ds.AddHeirarchicalTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); + + Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); + + // Act + termController.AddTerm(term); + + // Assert + Assert.AreEqual(Constants.TERM_AddTermId, term.TermId); + } + + [Test] + public void TermController_AddTerm_Clears_Term_Cache_On_Valid_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + + // Act + termController.AddTerm(term); + + // Assert + this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); + } + + [Test] + public void TermController_AddTermToContent_Throws_On_Null_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + ContentItem content = ContentTestHelper.CreateValidContentItem(); + + // Act, Arrange + Assert.Throws(() => termController.AddTermToContent(null, content)); + } + + [Test] + public void TermController_AddTermToContent_Throws_On_Null_ContentItem() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + + // Act, Arrange + Assert.Throws(() => termController.AddTermToContent(term, null)); + } + + [Test] + public void TermController_AddTermToContent_Should_Call_DataService_If_Valid_Params() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + ContentItem content = ContentTestHelper.CreateValidContentItem(); + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + + // Act + termController.AddTermToContent(term, content); + + // Assert + mockDataService.Verify(ds => ds.AddTermToContent(term, content)); + } + + [Test] + public void TermController_DeleteTerm_Throws_On_Null_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => termController.DeleteTerm(null)); + } + + [Test] + public void TermController_DeleteTerm_Throws_On_Negative_TermId() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + var term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + term.TermId = Null.NullInteger; + + // Act, Arrange + Assert.Throws(() => termController.DeleteTerm(term)); + } + + [Test] + public void TermController_DeleteTerm_Should_Call_DataService_DeleteSimpleTerm_If_Term_Is_Simple_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + var term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + term.TermId = Constants.TERM_DeleteTermId; + + // Act + termController.DeleteTerm(term); + + // Assert + mockDataService.Verify(ds => ds.DeleteSimpleTerm(term)); + } + + [Test] + public void TermController_DeleteTerm_Should_Call_DataService_DeleteHeirarchicalTerm_If_Term_Is_Heirarchical_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + var term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); + term.TermId = Constants.TERM_DeleteTermId; + + // Act + termController.DeleteTerm(term); + + // Assert + mockDataService.Verify(ds => ds.DeleteHeirarchicalTerm(term)); + } + + [Test] + public void TermController_DeleteTerm_Clears_Term_Cache_On_Valid_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + var term = new Term(Constants.VOCABULARY_ValidVocabularyId) { TermId = Constants.TERM_DeleteTermId }; + + // Act + termController.DeleteTerm(term); + + // Assert + this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); + } + + [Test] + public void TermController_GetTerm_Throws_On_Negative_TermId() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => termController.GetTerm(Null.NullInteger)); + } + + [Test] + public void TermController_GetTerm_Returns_Null_On_InValidTermId() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_InValidTermId)).Returns(MockHelper.CreateEmptyTermReader()); + + var termController = new TermController(mockDataService.Object); + + // Act + Term term = termController.GetTerm(Constants.TERM_InValidTermId); + + // Assert + Assert.IsNull(term); + } + + [Test] + public void TermController_GetTerm_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_ValidTermId)).Returns(MockHelper.CreateValidTermReader()); + var termController = new TermController(mockDataService.Object); + + // Act + Term term = termController.GetTerm(Constants.TERM_ValidTermId); + + // Assert + mockDataService.Verify(ds => ds.GetTerm(Constants.TERM_ValidTermId)); + } + + [Test] + public void TermController_GetTerm_Returns_Term_On_Valid_TermId() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_ValidTermId)).Returns(MockHelper.CreateValidTermReader()); + + var termController = new TermController(mockDataService.Object); + + // Act + var term = termController.GetTerm(Constants.TERM_ValidTermId); + + // Assert + Assert.AreEqual(Constants.TERM_ValidTermId, term.TermId); + Assert.AreEqual(Constants.TERM_ValidName, term.Name); + } + + [Test] + public void TermController_GetTermsByContent_Throws_On_Invalid_ContentItemId() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => termController.GetTermsByContent(Null.NullInteger)); + } + + [Test] + public void TermController_GetTermsByContent_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( + Constants.TERM_ValidCountForContent1, + v => Constants.TERM_ValidVocabularyId, + c => Constants.TERM_ValidContent1)); + var termController = new TermController(mockDataService.Object); + + // Act + IQueryable terms = termController.GetTermsByContent(Constants.TERM_ValidContent1); + + // Assert + mockDataService.Verify(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)); + } + + [Test] + public void TermController_GetTermsByContent_Returns_Terms_On_Valid_ContentItemId() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( + Constants.TERM_ValidCountForContent1, + v => Constants.TERM_ValidVocabularyId, + c => Constants.TERM_ValidContent1)); + + var termController = new TermController(mockDataService.Object); + + // Act + var terms = termController.GetTermsByContent(Constants.TERM_ValidContent1).ToList(); + + // Assert + Assert.AreEqual(Constants.TERM_ValidCountForContent1, terms.Count); + + for (int i = 0; i < Constants.TERM_ValidCountForContent1; i++) + { + Assert.AreEqual(i + Constants.TERM_ValidTermId, terms[i].TermId); + Assert.AreEqual(ContentTestHelper.GetTermName(i + Constants.TERM_ValidTermId), terms[i].Name); + } + } + + [Test] + public void TermController_GetTermsByVocabulary_Throws_On_Invalid_VocabularyId() + { + // Arrange + var mockDataService = new Mock(); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); + var termController = new TermController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => termController.GetTermsByVocabulary(Null.NullInteger)); + } + + [Test] + public void TermController_GetTermsByVocabulary_Returns_Terms_On_Valid_VocabularyId() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1)).Returns(MockHelper.CreateValidTermsReader( + Constants.TERM_ValidCountForVocabulary1, + v => Constants.TERM_ValidVocabulary1, + c => Constants.TERM_ValidContent1)); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); + + var termController = new TermController(mockDataService.Object); + + // Act + var terms = termController.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1).ToList(); + + // Assert + Assert.AreEqual(Constants.TERM_ValidCountForVocabulary1, terms.Count); + + for (int i = 0; i < Constants.TERM_ValidCountForVocabulary1; i++) + { + Assert.AreEqual(i + Constants.TERM_ValidTermId, terms[i].TermId); + Assert.AreEqual(ContentTestHelper.GetTermName(i + Constants.TERM_ValidTermId), terms[i].Name); + } + } + + [Test] + public void TermController_GetTermsByVocabulary_Throws_On_Invalid_VocabularyName() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => termController.GetTermsByVocabulary(Null.NullString)); + } + + [Test] + public void TermController_RemoveTermsFromContent_Throws_On_Null_ContentItem() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => termController.RemoveTermsFromContent(null)); + } + + [Test] + public void TermController_RemoveTermsFromContent_Should_Call_DataService_If_Valid_Params() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + ContentItem content = ContentTestHelper.CreateValidContentItem(); + + // Act + termController.RemoveTermsFromContent(content); + + // Assert + mockDataService.Verify(ds => ds.RemoveTermsFromContent(content)); + } + + [Test] + public void TermController_UpdateTerm_Throws_On_Null_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => termController.UpdateTerm(null)); + } + + [Test] + public void TermController_UpdateTerm_Throws_On_Negative_TermId() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); + + // Act, Arrange + Assert.Throws(() => termController.UpdateTerm(term)); + } + + [Test] + public void TermController_UpdateTerm_Throws_On_Invalid_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + term.Name = Constants.TERM_InValidName; + + // Act, Arrange + Assert.Throws(() => termController.UpdateTerm(term)); + } + + [Test] + public void TermController_UpdateTerm_Throws_On_Negative_VocabularyId() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); + + // Act, Arrange + Assert.Throws(() => termController.UpdateTerm(term)); + } + + [Test] + public void TermController_UpdateTerm_Should_Call_DataService_UpdateSimpleTerm_If_Term_Is_Simple_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + term.TermId = Constants.TERM_UpdateTermId; + term.Name = Constants.TERM_UpdateName; + term.Weight = Constants.TERM_UpdateWeight; + + // Act + termController.UpdateTerm(term); + + // Assert + mockDataService.Verify(ds => ds.UpdateSimpleTerm(term, UserController.Instance.GetCurrentUserInfo().UserID)); + } + + [Test] + public void TermController_UpdateTerm_Should_Call_DataService_UpdateHeirarchicalTerm_If_Term_Is_Heirarchical_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); + term.TermId = Constants.TERM_UpdateTermId; + term.Name = Constants.TERM_UpdateName; + term.Weight = Constants.TERM_UpdateWeight; + + // Act + termController.UpdateTerm(term); + + // Assert + mockDataService.Verify(ds => ds.UpdateHeirarchicalTerm(term, UserController.Instance.GetCurrentUserInfo().UserID)); + } + + [Test] + public void TermController_UpdateTerm_Clears_Term_Cache_On_Valid_Term() + { + // Arrange + var mockDataService = new Mock(); + var termController = new TermController(mockDataService.Object); + + Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); + term.TermId = Constants.TERM_UpdateTermId; + term.Name = Constants.TERM_UpdateName; + term.Weight = Constants.TERM_UpdateWeight; + + // Act + termController.UpdateTerm(term); + + // Assert + this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs index 82e483e1941..c141ad0f645 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs @@ -2,334 +2,336 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Content -{ - using System; +namespace DotNetNuke.Tests.Content +{ + using System; using System.Linq; using DotNetNuke.Abstractions; - using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Content.Data; - using DotNetNuke.Entities.Content.Taxonomy; - using DotNetNuke.Services.Cache; - using DotNetNuke.Tests.Content.Mocks; - using DotNetNuke.Tests.Utilities; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; using DotNetNuke.Tests.Utilities.Mocks; using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using NUnit.Framework; - - /// - /// Summary description for VocabularyTests. - /// - [TestFixture] - public class VocabularyControllerTests - { - private Mock mockCache; - - [SetUp] - public void SetUp() - { + + using Moq; + + using NUnit.Framework; + + /// + /// Summary description for VocabularyTests. + /// + [TestFixture] + public class VocabularyControllerTests + { + private Mock mockCache; + + [SetUp] + public void SetUp() + { var serviceCollection = new ServiceCollection(); serviceCollection.AddTransient(container => Mock.Of()); serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - // Register MockCachingProvider - this.mockCache = MockComponentProvider.CreateNew(); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); - } - - [TearDown] - public void TearDown() - { - Globals.DependencyProvider = null; - MockComponentProvider.ResetContainer(); - } - - [Test] - public void VocabularyController_AddVocabulary_Throws_On_Null_Vocabulary() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => vocabularyController.AddVocabulary(null)); - } - - [Test] - public void VocabularyController_AddVocabulary_Throws_On_Invalid_Name() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.Name = Constants.VOCABULARY_InValidName; - - // Act, Arrange - Assert.Throws(() => vocabularyController.AddVocabulary(vocabulary)); - } - - [Test] - public void VocabularyController_AddVocabulary_Throws_On_Negative_ScopeTypeID() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.ScopeTypeId = Null.NullInteger; - - // Act, Arrange - Assert.Throws(() => vocabularyController.AddVocabulary(vocabulary)); - } - - [Test] - public void VocabularyController_AddVocabulary_Calls_DataService_On_Valid_Arguments() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - - // Act - int vocabularyId = vocabularyController.AddVocabulary(vocabulary); - - // Assert - mockDataService.Verify(ds => ds.AddVocabulary(vocabulary, It.IsAny())); - } - - [Test] - public void VocabularyController_AddVocabulary_Returns_ValidId_On_Valid_Vocabulary() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.AddVocabulary(It.IsAny(), It.IsAny())).Returns(Constants.VOCABULARY_AddVocabularyId); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - - // Act - int vocabularyId = vocabularyController.AddVocabulary(vocabulary); - - // Assert - Assert.AreEqual(Constants.VOCABULARY_AddVocabularyId, vocabularyId); - } - - [Test] - public void VocabularyController_AddVocabulary_Sets_ValidId_On_Valid_Vocabulary() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.AddVocabulary(It.IsAny(), It.IsAny())).Returns(Constants.VOCABULARY_AddVocabularyId); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - - // Act - vocabularyController.AddVocabulary(vocabulary); - - // Assert - Assert.AreEqual(Constants.VOCABULARY_AddVocabularyId, vocabulary.VocabularyId); - } - - [Test] - public void VocabularyController_AddVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - - // Act - vocabularyController.AddVocabulary(vocabulary); - - // Assert - this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } - - [Test] - public void VocabularyController_DeleteVocabulary_Throws_On_Null_Vocabulary() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => vocabularyController.DeleteVocabulary(null)); - } - - [Test] - public void VocabularyController_DeleteVocabulary_Throws_On_Negative_VocabularyId() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = new Vocabulary(); - vocabulary.VocabularyId = Null.NullInteger; - - // Act, Arrange - Assert.Throws(() => vocabularyController.DeleteVocabulary(vocabulary)); - } - - [Test] - public void VocabularyController_DeleteVocabulary_Calls_DataService_On_Valid_Arguments() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.VocabularyId = Constants.VOCABULARY_ValidVocabularyId; - - // Act - vocabularyController.DeleteVocabulary(vocabulary); - - // Assert - mockDataService.Verify(ds => ds.DeleteVocabulary(vocabulary)); - } - - [Test] - public void VocabularyController_DeleteVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.VocabularyId = Constants.VOCABULARY_ValidVocabularyId; - - // Act - vocabularyController.DeleteVocabulary(vocabulary); - - // Assert - this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } - - [Test] - public void VocabularyController_GetVocabularies_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetVocabularies()).Returns(MockHelper.CreateValidVocabulariesReader(Constants.VOCABULARY_ValidCount)); - var vocabularyController = new VocabularyController(mockDataService.Object); - - // Act - IQueryable vocabularys = vocabularyController.GetVocabularies(); - - // Assert - mockDataService.Verify(ds => ds.GetVocabularies()); - } - - [Test] - public void VocabularyController_GetVocabularies_Returns_List_Of_Vocabularies() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetVocabularies()).Returns(MockHelper.CreateValidVocabulariesReader(Constants.VOCABULARY_ValidCount)); - var vocabularyController = new VocabularyController(mockDataService.Object); - - // Act - IQueryable vocabularys = vocabularyController.GetVocabularies(); - - // Assert - Assert.AreEqual(Constants.VOCABULARY_ValidCount, vocabularys.Count()); - } - - [Test] - public void VocabularyController_UpdateVocabulary_Throws_On_Null_Vocabulary() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - // Act, Arrange - Assert.Throws(() => vocabularyController.UpdateVocabulary(null)); - } - - [Test] - public void VocabularyController_UpdateVocabulary_Throws_On_Negative_VocabularyId() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.VocabularyId = Null.NullInteger; - - // Act, Arrange - Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); - } - - [Test] - public void VocabularyController_UpdateVocabulary_Throws_On_Invalid_Name() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.Name = Constants.VOCABULARY_InValidName; - - // Act, Arrange - Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); - } - - [Test] - public void VocabularyController_UpdateVocabulary_Throws_On_Negative_ScopeTypeID() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.ScopeTypeId = Null.NullInteger; - - // Act, Arrange - Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); - } - - [Test] - public void VocabularyController_UpdateVocabulary_Calls_DataService_On_Valid_Arguments() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.VocabularyId = Constants.VOCABULARY_UpdateVocabularyId; - - // Act - vocabularyController.UpdateVocabulary(vocabulary); - - // Assert - mockDataService.Verify(ds => ds.UpdateVocabulary(vocabulary, It.IsAny())); - } - - [Test] - public void VocabularyController__UpdateVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() - { - // Arrange - var mockDataService = new Mock(); - var vocabularyController = new VocabularyController(mockDataService.Object); - - Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - vocabulary.VocabularyId = Constants.VOCABULARY_UpdateVocabularyId; - - // Act - vocabularyController.UpdateVocabulary(vocabulary); - - // Assert - this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } - } -} + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + // Register MockCachingProvider + this.mockCache = MockComponentProvider.CreateNew(); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + MockComponentProvider.ResetContainer(); + } + + [Test] + public void VocabularyController_AddVocabulary_Throws_On_Null_Vocabulary() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => vocabularyController.AddVocabulary(null)); + } + + [Test] + public void VocabularyController_AddVocabulary_Throws_On_Invalid_Name() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.Name = Constants.VOCABULARY_InValidName; + + // Act, Arrange + Assert.Throws(() => vocabularyController.AddVocabulary(vocabulary)); + } + + [Test] + public void VocabularyController_AddVocabulary_Throws_On_Negative_ScopeTypeID() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.ScopeTypeId = Null.NullInteger; + + // Act, Arrange + Assert.Throws(() => vocabularyController.AddVocabulary(vocabulary)); + } + + [Test] + public void VocabularyController_AddVocabulary_Calls_DataService_On_Valid_Arguments() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + + // Act + int vocabularyId = vocabularyController.AddVocabulary(vocabulary); + + // Assert + mockDataService.Verify(ds => ds.AddVocabulary(vocabulary, It.IsAny())); + } + + [Test] + public void VocabularyController_AddVocabulary_Returns_ValidId_On_Valid_Vocabulary() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.AddVocabulary(It.IsAny(), It.IsAny())).Returns(Constants.VOCABULARY_AddVocabularyId); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + + // Act + int vocabularyId = vocabularyController.AddVocabulary(vocabulary); + + // Assert + Assert.AreEqual(Constants.VOCABULARY_AddVocabularyId, vocabularyId); + } + + [Test] + public void VocabularyController_AddVocabulary_Sets_ValidId_On_Valid_Vocabulary() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.AddVocabulary(It.IsAny(), It.IsAny())).Returns(Constants.VOCABULARY_AddVocabularyId); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + + // Act + vocabularyController.AddVocabulary(vocabulary); + + // Assert + Assert.AreEqual(Constants.VOCABULARY_AddVocabularyId, vocabulary.VocabularyId); + } + + [Test] + public void VocabularyController_AddVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + + // Act + vocabularyController.AddVocabulary(vocabulary); + + // Assert + this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); + } + + [Test] + public void VocabularyController_DeleteVocabulary_Throws_On_Null_Vocabulary() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => vocabularyController.DeleteVocabulary(null)); + } + + [Test] + public void VocabularyController_DeleteVocabulary_Throws_On_Negative_VocabularyId() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = new Vocabulary(); + vocabulary.VocabularyId = Null.NullInteger; + + // Act, Arrange + Assert.Throws(() => vocabularyController.DeleteVocabulary(vocabulary)); + } + + [Test] + public void VocabularyController_DeleteVocabulary_Calls_DataService_On_Valid_Arguments() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.VocabularyId = Constants.VOCABULARY_ValidVocabularyId; + + // Act + vocabularyController.DeleteVocabulary(vocabulary); + + // Assert + mockDataService.Verify(ds => ds.DeleteVocabulary(vocabulary)); + } + + [Test] + public void VocabularyController_DeleteVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.VocabularyId = Constants.VOCABULARY_ValidVocabularyId; + + // Act + vocabularyController.DeleteVocabulary(vocabulary); + + // Assert + this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); + } + + [Test] + public void VocabularyController_GetVocabularies_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetVocabularies()).Returns(MockHelper.CreateValidVocabulariesReader(Constants.VOCABULARY_ValidCount)); + var vocabularyController = new VocabularyController(mockDataService.Object); + + // Act + IQueryable vocabularys = vocabularyController.GetVocabularies(); + + // Assert + mockDataService.Verify(ds => ds.GetVocabularies()); + } + + [Test] + public void VocabularyController_GetVocabularies_Returns_List_Of_Vocabularies() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetVocabularies()).Returns(MockHelper.CreateValidVocabulariesReader(Constants.VOCABULARY_ValidCount)); + var vocabularyController = new VocabularyController(mockDataService.Object); + + // Act + IQueryable vocabularys = vocabularyController.GetVocabularies(); + + // Assert + Assert.AreEqual(Constants.VOCABULARY_ValidCount, vocabularys.Count()); + } + + [Test] + public void VocabularyController_UpdateVocabulary_Throws_On_Null_Vocabulary() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + // Act, Arrange + Assert.Throws(() => vocabularyController.UpdateVocabulary(null)); + } + + [Test] + public void VocabularyController_UpdateVocabulary_Throws_On_Negative_VocabularyId() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.VocabularyId = Null.NullInteger; + + // Act, Arrange + Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); + } + + [Test] + public void VocabularyController_UpdateVocabulary_Throws_On_Invalid_Name() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.Name = Constants.VOCABULARY_InValidName; + + // Act, Arrange + Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); + } + + [Test] + public void VocabularyController_UpdateVocabulary_Throws_On_Negative_ScopeTypeID() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.ScopeTypeId = Null.NullInteger; + + // Act, Arrange + Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); + } + + [Test] + public void VocabularyController_UpdateVocabulary_Calls_DataService_On_Valid_Arguments() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.VocabularyId = Constants.VOCABULARY_UpdateVocabularyId; + + // Act + vocabularyController.UpdateVocabulary(vocabulary); + + // Assert + mockDataService.Verify(ds => ds.UpdateVocabulary(vocabulary, It.IsAny())); + } + + [Test] + public void VocabularyController__UpdateVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() + { + // Arrange + var mockDataService = new Mock(); + var vocabularyController = new VocabularyController(mockDataService.Object); + + Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); + vocabulary.VocabularyId = Constants.VOCABULARY_UpdateVocabularyId; + + // Act + vocabularyController.UpdateVocabulary(vocabulary); + + // Assert + this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs index b8a9326f001..652f571e410 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs @@ -2,405 +2,417 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Common -{ - using System.Collections.Generic; - using System.Linq; - - using DotNetNuke.Abstractions; - using DotNetNuke.Abstractions.Portals; - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Tabs; - using DotNetNuke.Services.Localization; - using Moq; - using NUnit.Framework; - - [TestFixture] - public class NavigationManagerTests - { - private const int TabID = 100; - private const int PortalID = 7; - private const string DefaultURLPattern = "/Default.aspx?tabid={0}"; - private const string DefaultSuperTabPattern = "&portalid={0}"; - private const string ControlKeyPattern = "&ctl={0}"; - private const string LanguagePattern = "&language={0}"; - private INavigationManager _navigationManager; - - [TestFixtureSetUp] - public void Setup() - { - this._navigationManager = new NavigationManager(PortalControllerMock()); - TabController.SetTestableInstance(TabControllerMock()); - LocaleController.SetTestableInstance(LocaleControllerMock()); - - IPortalController PortalControllerMock() - { - var mockPortalController = new Mock(); - mockPortalController - .Setup(x => x.GetCurrentPortalSettings()) - .Returns(PortalSettingsMock()); - mockPortalController - .Setup(x => x.GetCurrentSettings()) - .Returns(PortalSettingsMock()); - - return mockPortalController.Object; - - PortalSettings PortalSettingsMock() - { - var portalSettings = new PortalSettings - { - PortalId = PortalID, - ActiveTab = new TabInfo - { - TabID = TabID - }, - }; - - return portalSettings; - } - } - - ITabController TabControllerMock() - { - var mockTabController = new Mock(); - mockTabController - .Setup(x => x.GetTabsByPortal(Null.NullInteger)) - .Returns(default(TabCollection)); - mockTabController - .Setup(x => x.GetTab(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(new TabInfo - { - CultureCode = "en-US", - }); - - return mockTabController.Object; - } - - ILocaleController LocaleControllerMock() - { - var mockLocaleController = new Mock(); - mockLocaleController - .Setup(x => x.GetLocales(It.IsAny())) - .Returns(new Dictionary - { - { "en-US", new Locale() }, - { "TEST", new Locale() }, - }); - - return mockLocaleController.Object; - } - } - - [TestFixtureTearDown] - public void TearDown() - { - this._navigationManager = null; - TabController.ClearInstance(); - LocaleController.ClearInstance(); - } - - [Test] - public void NavigateUrlTest() - { - var expected = string.Format(DefaultURLPattern, TabID); - var actual = this._navigationManager.NavigateURL(); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(1)] - [TestCase(2)] - [TestCase(3)] - [TestCase(4)] - [TestCase(5)] - [TestCase(6)] - [TestCase(7)] - [TestCase(8)] - [TestCase(9)] - [TestCase(10)] - [TestCase(11)] - public void NavigateUrl_CustomTabID(int tabId) - { - var expected = string.Format(DefaultURLPattern, tabId); - var actual = this._navigationManager.NavigateURL(tabId); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [Test] - public void NavigateUrl_CustomTab_NotSuperTab() - { - var customTabId = 55; - var expected = string.Format(DefaultURLPattern, customTabId); - var actual = this._navigationManager.NavigateURL(customTabId, false); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(1)] - [TestCase(2)] - [TestCase(3)] - [TestCase(4)] - [TestCase(5)] - [TestCase(6)] - [TestCase(7)] - [TestCase(8)] - [TestCase(9)] - [TestCase(10)] - [TestCase(11)] - public void NavigateUrl_CustomTab_IsSuperTab(int tabId) - { - var expected = string.Format(DefaultURLPattern, tabId) + string.Format(DefaultSuperTabPattern, PortalID); - var actual = this._navigationManager.NavigateURL(tabId, true); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [Test] - [Ignore] - public void NavigateUrl_ControlKey_AccessDenied() - { - // TODO - We can't properly test this until we migrate - // Globals.AccessDeniedURL to an interface in the abstraction - // project. The dependencies go very deep and make it very - // difficult to properly test just the NavigationManager logic. - var actual = this._navigationManager.NavigateURL("Access Denied"); - } - - [Test] - public void NavigateUrl_ControlKey() - { - var controlKey = "My-Control-Key"; - var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey); - var actual = this._navigationManager.NavigateURL(controlKey); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [Test] - public void NavigateUrl_ControlKey_EmptyAdditionalParameter() - { - var controlKey = "My-Control-Key"; - var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey); - var actual = this._navigationManager.NavigateURL(controlKey, new string[0]); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [Test] - public void NavigateUrl_ControlKey_SingleAdditionalParameter() - { - var controlKey = "My-Control-Key"; - var parameters = new string[] { "My-Parameter" }; - var expected = string.Format(DefaultURLPattern, TabID) + - string.Format(ControlKeyPattern, controlKey) + - $"&{parameters[0]}"; - var actual = this._navigationManager.NavigateURL(controlKey, parameters); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(2)] - [TestCase(3)] - [TestCase(4)] - [TestCase(5)] - [TestCase(6)] - [TestCase(7)] - [TestCase(8)] - [TestCase(9)] - [TestCase(10)] - public void NavigateUrl_ControlKey_MultipleAdditionalParameter(int count) - { - string[] parameters = new string[count]; - for (int index = 0; index < count; index++) - { - parameters[index] = $"My-Parameter{index}"; - } - - var controlKey = "My-Control-Key"; - var expected = string.Format(DefaultURLPattern, TabID) + - string.Format(ControlKeyPattern, controlKey) + - parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); - var actual = this._navigationManager.NavigateURL(controlKey, parameters); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(1)] - [TestCase(2)] - [TestCase(3)] - [TestCase(4)] - [TestCase(5)] - [TestCase(6)] - [TestCase(7)] - [TestCase(8)] - [TestCase(9)] - [TestCase(10)] - [TestCase(11)] - public void NavigateUrl_TabID_ControlKey(int tabId) - { - var controlKey = "My-Control-Key"; - var expected = string.Format(DefaultURLPattern, tabId) + string.Format(ControlKeyPattern, controlKey); - var actual = this._navigationManager.NavigateURL(tabId, controlKey); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(1)] - [TestCase(2)] - [TestCase(3)] - [TestCase(4)] - [TestCase(5)] - [TestCase(6)] - [TestCase(7)] - [TestCase(8)] - [TestCase(9)] - [TestCase(10)] - [TestCase(11)] - public void NavigateUrl_TabID_EmptyControlKey(int tabId) - { - var expected = string.Format(DefaultURLPattern, tabId); - var actual = this._navigationManager.NavigateURL(tabId, string.Empty); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(1)] - [TestCase(2)] - [TestCase(3)] - [TestCase(4)] - [TestCase(5)] - [TestCase(6)] - [TestCase(7)] - [TestCase(8)] - [TestCase(9)] - [TestCase(10)] - [TestCase(11)] - public void NavigateUrl_TabID_NullControlKey(int tabId) - { - var expected = string.Format(DefaultURLPattern, tabId); - var actual = this._navigationManager.NavigateURL(tabId, string.Empty); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(0, "My-Control-Key-0")] - [TestCase(1, "My-Control-Key-1")] - [TestCase(2, "My-Control-Key-2")] - [TestCase(3, "My-Control-Key-3")] - [TestCase(4, "My-Control-Key-4")] - [TestCase(5, "My-Control-Key-5")] - [TestCase(6, "My-Control-Key-6")] - [TestCase(7, "My-Control-Key-7")] - [TestCase(8, "My-Control-Key-8")] - [TestCase(9, "My-Control-Key-9")] - [TestCase(10, "My-Control-Key-10")] - public void NavigateUrl_TabID_ControlKey_Parameter(int count, string controlKey) - { - string[] parameters = new string[count]; - for (int index = 0; index < count; index++) - { - parameters[index] = $"My-Parameter{index}"; - } - - var customTabId = 51; - var expected = string.Format(DefaultURLPattern, customTabId) + - string.Format(ControlKeyPattern, controlKey); - - if (parameters.Length > 0) - { - expected += parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); - } - - var actual = this._navigationManager.NavigateURL(customTabId, controlKey, parameters); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(0, "My-Control-Key-0")] - [TestCase(1, "My-Control-Key-1")] - [TestCase(2, "My-Control-Key-2")] - [TestCase(3, "My-Control-Key-3")] - [TestCase(4, "My-Control-Key-4")] - [TestCase(5, "My-Control-Key-5")] - [TestCase(6, "My-Control-Key-6")] - [TestCase(7, "My-Control-Key-7")] - [TestCase(8, "My-Control-Key-8")] - [TestCase(9, "My-Control-Key-9")] - [TestCase(10, "My-Control-Key-10")] - public void NavigateUrl_TabID_ControlKey_NullParameter(int tabId, string controlKey) - { - var expected = string.Format(DefaultURLPattern, tabId) + - string.Format(ControlKeyPattern, controlKey); - - var actual = this._navigationManager.NavigateURL(tabId, controlKey, null); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(0, "My-Control-Key-0")] - [TestCase(1, "My-Control-Key-1")] - [TestCase(2, "My-Control-Key-2")] - [TestCase(3, "My-Control-Key-3")] - [TestCase(4, "My-Control-Key-4")] - [TestCase(5, "My-Control-Key-5")] - [TestCase(6, "My-Control-Key-6")] - [TestCase(7, "My-Control-Key-7")] - [TestCase(8, "My-Control-Key-8")] - [TestCase(9, "My-Control-Key-9")] - [TestCase(10, "My-Control-Key-10")] - public void NavigateUrl_TabId_NullSettings_ControlKey(int tabId, string controlKey) - { - var expected = string.Format(DefaultURLPattern, tabId) + - string.Format(ControlKeyPattern, controlKey); - - var actual = this._navigationManager.NavigateURL(tabId, default(IPortalSettings), controlKey, null); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - - [TestCase(0, "My-Control-Key-0")] - [TestCase(1, "My-Control-Key-1")] - [TestCase(2, "My-Control-Key-2")] - [TestCase(3, "My-Control-Key-3")] - [TestCase(4, "My-Control-Key-4")] - [TestCase(5, "My-Control-Key-5")] - [TestCase(6, "My-Control-Key-6")] - [TestCase(7, "My-Control-Key-7")] - [TestCase(8, "My-Control-Key-8")] - [TestCase(9, "My-Control-Key-9")] - [TestCase(10, "My-Control-Key-10")] - public void NavigateUrl_TabId_Settings_ControlKey(int tabId, string controlKey) - { - var mockSettings = new Mock(); - mockSettings - .Setup(x => x.ContentLocalizationEnabled) - .Returns(true); - - var expected = string.Format(DefaultURLPattern, tabId) + - string.Format(ControlKeyPattern, controlKey) + - string.Format(LanguagePattern, "en-US"); - - var actual = this._navigationManager.NavigateURL(tabId, mockSettings.Object, controlKey, null); - - Assert.IsNotNull(actual); - Assert.AreEqual(expected, actual); - } - } -} +namespace DotNetNuke.Tests.Core.Common +{ + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class NavigationManagerTests + { + private const int TabID = 100; + private const int PortalID = 7; + private const string DefaultURLPattern = "/Default.aspx?tabid={0}"; + private const string DefaultSuperTabPattern = "&portalid={0}"; + private const string ControlKeyPattern = "&ctl={0}"; + private const string LanguagePattern = "&language={0}"; + private INavigationManager navigationManager; + + [TestFixtureSetUp] + public void Setup() + { + this.navigationManager = new NavigationManager(PortalControllerMock()); + TabController.SetTestableInstance(TabControllerMock()); + LocaleController.SetTestableInstance(LocaleControllerMock()); + + IPortalController PortalControllerMock() + { + var mockPortalController = new Mock(); + mockPortalController + .Setup(x => x.GetCurrentPortalSettings()) + .Returns(PortalSettingsMock()); + mockPortalController + .Setup(x => x.GetCurrentSettings()) + .Returns(PortalSettingsMock()); + + return mockPortalController.Object; + + PortalSettings PortalSettingsMock() + { + var portalSettings = new PortalSettings + { + PortalId = PortalID, + ActiveTab = new TabInfo + { + TabID = TabID + }, + }; + + return portalSettings; + } + } + + ITabController TabControllerMock() + { + var mockTabController = new Mock(); + mockTabController + .Setup(x => x.GetTabsByPortal(Null.NullInteger)) + .Returns(default(TabCollection)); + mockTabController + .Setup(x => x.GetTab(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(new TabInfo + { + CultureCode = "en-US", + }); + + return mockTabController.Object; + } + + ILocaleController LocaleControllerMock() + { + var mockLocaleController = new Mock(); + mockLocaleController + .Setup(x => x.GetLocales(It.IsAny())) + .Returns(new Dictionary + { + { "en-US", new Locale() }, + { "TEST", new Locale() }, + }); + + return mockLocaleController.Object; + } + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => this.navigationManager); + serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [TestFixtureTearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + this.navigationManager = null; + TabController.ClearInstance(); + LocaleController.ClearInstance(); + } + + [Test] + public void NavigateUrlTest() + { + var expected = string.Format(DefaultURLPattern, TabID); + var actual = this.navigationManager.NavigateURL(); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [TestCase(6)] + [TestCase(7)] + [TestCase(8)] + [TestCase(9)] + [TestCase(10)] + [TestCase(11)] + public void NavigateUrl_CustomTabID(int tabId) + { + var expected = string.Format(DefaultURLPattern, tabId); + var actual = this.navigationManager.NavigateURL(tabId); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [Test] + public void NavigateUrl_CustomTab_NotSuperTab() + { + var customTabId = 55; + var expected = string.Format(DefaultURLPattern, customTabId); + var actual = this.navigationManager.NavigateURL(customTabId, false); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [TestCase(6)] + [TestCase(7)] + [TestCase(8)] + [TestCase(9)] + [TestCase(10)] + [TestCase(11)] + public void NavigateUrl_CustomTab_IsSuperTab(int tabId) + { + var expected = string.Format(DefaultURLPattern, tabId) + string.Format(DefaultSuperTabPattern, PortalID); + var actual = this.navigationManager.NavigateURL(tabId, true); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [Test] + [Ignore] + public void NavigateUrl_ControlKey_AccessDenied() + { + // TODO - We can't properly test this until we migrate + // Globals.AccessDeniedURL to an interface in the abstraction + // project. The dependencies go very deep and make it very + // difficult to properly test just the NavigationManager logic. + var actual = this.navigationManager.NavigateURL("Access Denied"); + } + + [Test] + public void NavigateUrl_ControlKey() + { + var controlKey = "My-Control-Key"; + var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey); + var actual = this.navigationManager.NavigateURL(controlKey); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [Test] + public void NavigateUrl_ControlKey_EmptyAdditionalParameter() + { + var controlKey = "My-Control-Key"; + var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey); + var actual = this.navigationManager.NavigateURL(controlKey, new string[0]); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [Test] + public void NavigateUrl_ControlKey_SingleAdditionalParameter() + { + var controlKey = "My-Control-Key"; + var parameters = new string[] { "My-Parameter" }; + var expected = string.Format(DefaultURLPattern, TabID) + + string.Format(ControlKeyPattern, controlKey) + + $"&{parameters[0]}"; + var actual = this.navigationManager.NavigateURL(controlKey, parameters); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [TestCase(6)] + [TestCase(7)] + [TestCase(8)] + [TestCase(9)] + [TestCase(10)] + public void NavigateUrl_ControlKey_MultipleAdditionalParameter(int count) + { + string[] parameters = new string[count]; + for (int index = 0; index < count; index++) + { + parameters[index] = $"My-Parameter{index}"; + } + + var controlKey = "My-Control-Key"; + var expected = string.Format(DefaultURLPattern, TabID) + + string.Format(ControlKeyPattern, controlKey) + + parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); + var actual = this.navigationManager.NavigateURL(controlKey, parameters); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [TestCase(6)] + [TestCase(7)] + [TestCase(8)] + [TestCase(9)] + [TestCase(10)] + [TestCase(11)] + public void NavigateUrl_TabID_ControlKey(int tabId) + { + var controlKey = "My-Control-Key"; + var expected = string.Format(DefaultURLPattern, tabId) + string.Format(ControlKeyPattern, controlKey); + var actual = this.navigationManager.NavigateURL(tabId, controlKey); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [TestCase(6)] + [TestCase(7)] + [TestCase(8)] + [TestCase(9)] + [TestCase(10)] + [TestCase(11)] + public void NavigateUrl_TabID_EmptyControlKey(int tabId) + { + var expected = string.Format(DefaultURLPattern, tabId); + var actual = this.navigationManager.NavigateURL(tabId, string.Empty); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [TestCase(6)] + [TestCase(7)] + [TestCase(8)] + [TestCase(9)] + [TestCase(10)] + [TestCase(11)] + public void NavigateUrl_TabID_NullControlKey(int tabId) + { + var expected = string.Format(DefaultURLPattern, tabId); + var actual = this.navigationManager.NavigateURL(tabId, string.Empty); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(0, "My-Control-Key-0")] + [TestCase(1, "My-Control-Key-1")] + [TestCase(2, "My-Control-Key-2")] + [TestCase(3, "My-Control-Key-3")] + [TestCase(4, "My-Control-Key-4")] + [TestCase(5, "My-Control-Key-5")] + [TestCase(6, "My-Control-Key-6")] + [TestCase(7, "My-Control-Key-7")] + [TestCase(8, "My-Control-Key-8")] + [TestCase(9, "My-Control-Key-9")] + [TestCase(10, "My-Control-Key-10")] + public void NavigateUrl_TabID_ControlKey_Parameter(int count, string controlKey) + { + string[] parameters = new string[count]; + for (int index = 0; index < count; index++) + { + parameters[index] = $"My-Parameter{index}"; + } + + var customTabId = 51; + var expected = string.Format(DefaultURLPattern, customTabId) + + string.Format(ControlKeyPattern, controlKey); + + if (parameters.Length > 0) + { + expected += parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); + } + + var actual = this.navigationManager.NavigateURL(customTabId, controlKey, parameters); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(0, "My-Control-Key-0")] + [TestCase(1, "My-Control-Key-1")] + [TestCase(2, "My-Control-Key-2")] + [TestCase(3, "My-Control-Key-3")] + [TestCase(4, "My-Control-Key-4")] + [TestCase(5, "My-Control-Key-5")] + [TestCase(6, "My-Control-Key-6")] + [TestCase(7, "My-Control-Key-7")] + [TestCase(8, "My-Control-Key-8")] + [TestCase(9, "My-Control-Key-9")] + [TestCase(10, "My-Control-Key-10")] + public void NavigateUrl_TabID_ControlKey_NullParameter(int tabId, string controlKey) + { + var expected = string.Format(DefaultURLPattern, tabId) + + string.Format(ControlKeyPattern, controlKey); + + var actual = this.navigationManager.NavigateURL(tabId, controlKey, null); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(0, "My-Control-Key-0")] + [TestCase(1, "My-Control-Key-1")] + [TestCase(2, "My-Control-Key-2")] + [TestCase(3, "My-Control-Key-3")] + [TestCase(4, "My-Control-Key-4")] + [TestCase(5, "My-Control-Key-5")] + [TestCase(6, "My-Control-Key-6")] + [TestCase(7, "My-Control-Key-7")] + [TestCase(8, "My-Control-Key-8")] + [TestCase(9, "My-Control-Key-9")] + [TestCase(10, "My-Control-Key-10")] + public void NavigateUrl_TabId_NullSettings_ControlKey(int tabId, string controlKey) + { + var expected = string.Format(DefaultURLPattern, tabId) + + string.Format(ControlKeyPattern, controlKey); + + var actual = this.navigationManager.NavigateURL(tabId, default(IPortalSettings), controlKey, null); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + + [TestCase(0, "My-Control-Key-0")] + [TestCase(1, "My-Control-Key-1")] + [TestCase(2, "My-Control-Key-2")] + [TestCase(3, "My-Control-Key-3")] + [TestCase(4, "My-Control-Key-4")] + [TestCase(5, "My-Control-Key-5")] + [TestCase(6, "My-Control-Key-6")] + [TestCase(7, "My-Control-Key-7")] + [TestCase(8, "My-Control-Key-8")] + [TestCase(9, "My-Control-Key-9")] + [TestCase(10, "My-Control-Key-10")] + public void NavigateUrl_TabId_Settings_ControlKey(int tabId, string controlKey) + { + var mockSettings = new Mock(); + mockSettings + .Setup(x => x.ContentLocalizationEnabled) + .Returns(true); + + var expected = string.Format(DefaultURLPattern, tabId) + + string.Format(ControlKeyPattern, controlKey) + + string.Format(LanguagePattern, "en-US"); + + var actual = this.navigationManager.NavigateURL(tabId, mockSettings.Object, controlKey, null); + + Assert.IsNotNull(actual); + Assert.AreEqual(expected, actual); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs index 4da0b21a1c8..5a4a5698ecb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs @@ -2,415 +2,417 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Controllers.Host -{ - using System; - using System.Collections.Generic; - using System.Data; +namespace DotNetNuke.Tests.Core.Controllers.Host +{ + using System; + using System.Collections.Generic; + using System.Data; using System.Linq; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Entities; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Services.Cache; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; using DotNetNuke.Tests.Utilities.Mocks; using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using NUnit.Framework; - - [TestFixture] - public class HostControllerTest - { - private DataTable _hostSettingsTable; - private Mock _mockCache; - private Mock _mockData; - - [SetUp] - public void SetUp() - { - var serviceCollection = new ServiceCollection(); + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class HostControllerTest + { + private DataTable _hostSettingsTable; + private Mock _mockCache; + private Mock _mockData; + + [SetUp] + public void SetUp() + { + var serviceCollection = new ServiceCollection(); var mockApplicationStatusInfo = new Mock(); mockApplicationStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.Install); serviceCollection.AddTransient(container => Mock.Of()); serviceCollection.AddTransient(container => mockApplicationStatusInfo.Object); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - this._mockCache = MockComponentProvider.CreateDataCacheProvider(); - MockComponentProvider.CreateEventLogController(); - - this._hostSettingsTable = new DataTable("HostSettings"); - - var nameCol = this._hostSettingsTable.Columns.Add("SettingName"); - this._hostSettingsTable.Columns.Add("SettingValue"); - this._hostSettingsTable.Columns.Add("SettingIsSecure"); - this._hostSettingsTable.PrimaryKey = new[] { nameCol }; - - this._hostSettingsTable.Rows.Add("String_1_S", "String_1_S", true); - this._hostSettingsTable.Rows.Add("String_2_S", "String_1_S", true); - this._hostSettingsTable.Rows.Add("String_3_U", "Value_3_U", false); - this._hostSettingsTable.Rows.Add("String_4_U", "Value_4_U", false); - this._hostSettingsTable.Rows.Add("Int_5_U", "5", false); - this._hostSettingsTable.Rows.Add("Int_6_S", "6", true); - this._hostSettingsTable.Rows.Add("Double_7_S", "7", true); - this._hostSettingsTable.Rows.Add("Double_8_U", "8", false); - this._hostSettingsTable.Rows.Add("Bool_9_U", false, false); - this._hostSettingsTable.Rows.Add("Bool_10_S", false, true); - - this._mockData = MockComponentProvider.CreateDataProvider(); - this._mockData.Setup(c => c.GetHostSettings()).Returns(this._hostSettingsTable.CreateDataReader()); - this._mockData.Setup(c => c.GetProviderPath()).Returns(string.Empty); - - DataCache.ClearCache(); - } - - [TearDown] - public void TearDown() - { - Globals.DependencyProvider = null; - MockComponentProvider.ResetContainer(); - } - - [Test] - public void HostController_GetSettings_GetList() - { - // Arrange - var expectedDic = new Dictionary(); - - foreach (DataRow row in this._hostSettingsTable.Rows) - { - var conf = new ConfigurationSetting(); - conf.Key = row["SettingName"].ToString(); - conf.Value = row["SettingValue"].ToString(); - bool IsSecure; - bool.TryParse(row["SettingIsSecure"].ToString(), out IsSecure); - conf.IsSecure = IsSecure; - expectedDic.Add(conf.Key, conf); - } - - // Act - var settingsDic = HostController.Instance.GetSettings(); - - // Assert - foreach (var currentConfig in settingsDic) - { - Assert.AreEqual(currentConfig.Key, currentConfig.Value.Key); - Assert.AreEqual(expectedDic[currentConfig.Key].Value, currentConfig.Value.Value); - Assert.AreEqual(expectedDic[currentConfig.Key].IsSecure, currentConfig.Value.IsSecure); - } - } - - [Test] - public void HostController_GetSettingsDictionary_GetList() - { - // Arrange - // Convert table to Dictionary - var expectedDic = this._hostSettingsTable.Rows.Cast().ToDictionary(row => row["SettingName"].ToString(), row => row["SettingValue"].ToString()); - - // Act - var settingsDic = HostController.Instance.GetSettingsDictionary(); - - // Assert - CollectionAssert.AreEquivalent(expectedDic.Values, settingsDic.Values); - } - - [Test] - public void HostController_Update_ExistingValue() - { - // Arrange - const string key = "String_1_S"; - const string value = "MyValue"; - this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); - - // Act - HostController.Instance.Update(key, value); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); - this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); - } - - [Test] - public void HostController_Update_ExistingValue_ResetCache() - { - // Arrange - const string key = "String_1_S"; - const string value = "MyValue"; - this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); - - // Act - HostController.Instance.Update(key, value); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); - this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); - } - - [Test] - public void HostController_Update_ExistingValue_ResetCache_With_Overload() - { - // Arrange - const string key = "String_1_S"; - const string value = "MyValue"; - this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); - - // Act - HostController.Instance.Update(key, value, true); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); - this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); - } - - [Test] - public void HostController_Update_ExistingValue_Dont_Reset_Cache() - { - // Arrange - const string key = "String_1_S"; - const string value = "MyValue"; - this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); - - // Act - HostController.Instance.Update(key, value, false); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - - // Clear was not called a second time - this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); - } - - [Test] - public void HostController_Update_Dictionary() - { - // Arrange - var settings = new Dictionary - { - { "String_1_S", "MyValue" }, - }; - - // Act - HostController.Instance.Update(settings); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting("String_1_S", "MyValue", false, It.IsAny()), Times.Exactly(1)); - this._mockCache.Verify(c => c.Clear("Host", string.Empty), Times.Exactly(1)); - } - - [Test] - public void HostController_Update_NewValue() - { - // Arrange - const string key = "MyKey"; - const string value = "MyValue"; - this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); - - // Act - HostController.Instance.Update(key, value); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); - } - - [Test] - public void HostController_Update_NewValue_ResetCache_With_Overload() - { - // Arrange - const string key = "MyKey"; - const string value = "MyValue"; - this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); - - // Act - HostController.Instance.Update(key, value, true); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); - } - - [Test] - public void HostController_Update_NewValue_ResetCache() - { - // Arrange - const string key = "MyKey"; - const string value = "MyValue"; - this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); - - // Act - HostController.Instance.Update(key, value); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); - } - - [Test] - public void HostController_Update_NewValue_Dont_Reset_Cache() - { - // Arrange - const string key = "MyKey"; - const string value = "MyValue"; - this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); - - // Act - HostController.Instance.Update(key, value, false); - - // Assert - this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); - } - - [Test] - [TestCase("String_1_S")] - [TestCase("String_2_S")] - [TestCase("String_3_U")] - [TestCase("String_4_U")] - public void HostController_GetString_If_Key_Exists(string key) - { - Assert.AreEqual(HostController.Instance.GetString(key), this.GetValue(key)); - Assert.AreEqual(HostController.Instance.GetString(key, "Hello Default"), this.GetValue(key)); - } - - [Test] - [TestCase("BadKey1")] - [TestCase("AAAAAAA")] - public void HostController_GetString_InvalidKey_Returns_Null_Value(string key) - { - Assert.AreEqual(HostController.Instance.GetString(key), Null.NullString); - } - - [Test] - [TestCase("BadKey1")] - [TestCase("AAAAAAA")] - public void HostController_GetString_InvalidKey_Returns_Default_Value(string key) - { - Assert.AreEqual(HostController.Instance.GetString(key, "Hello Default"), "Hello Default"); - } - - [Test] - [TestCase("")] - [TestCase(null)] - [ExpectedException(typeof(ArgumentException))] - public void HostController_GetString_NullEmpty(string key) - { - HostController.Instance.GetString(key); - } - - [Test] - [TestCase("Int_5_U")] - [TestCase("Int_6_S")] - public void HostController_GetInteger_If_Key_Exists(string key) - { - int s = HostController.Instance.GetInteger(key); - Assert.AreEqual(s.ToString(), this.GetValue(key)); - Assert.AreEqual(HostController.Instance.GetInteger(key, 12).ToString(), this.GetValue(key)); - } - - [Test] - [TestCase("BadKey1")] - [TestCase("AAAAAAA")] - public void HostController_GetInteger_InvalidKey_Returns_Null_Value(string key) - { - Assert.AreEqual(HostController.Instance.GetInteger(key), Null.NullInteger); - } - - [Test] - [TestCase("BadKey1")] - [TestCase("AAAAAAA")] - public void HostController_GetInteger_InvalidKey_Returns_Default_Value(string key) - { - Assert.AreEqual(HostController.Instance.GetInteger(key, 6969), 6969); - } - - [Test] - [TestCase("")] - [TestCase(null)] - [ExpectedException(typeof(ArgumentException))] - public void HostController_GetInteger_NullEmpty(string key) - { - HostController.Instance.GetInteger(key); - } - - [Test] - [TestCase("Bool_9_U")] - [TestCase("Bool_10_S")] - public void HostController_GetBoolean_If_Key_Exists(string key) - { - Assert.AreEqual(HostController.Instance.GetBoolean(key).ToString(), this.GetValue(key)); - Assert.AreEqual(HostController.Instance.GetBoolean(key, false).ToString(), this.GetValue(key)); - Assert.AreEqual(HostController.Instance.GetBoolean(key, true).ToString(), this.GetValue(key)); - } - - [Test] - [TestCase("BadKey1")] - [TestCase("AAAAAAA")] - public void HostController_GetBoolean_InvalidKey_Returns_Null_Value(string key) - { - Assert.AreEqual(HostController.Instance.GetBoolean(key), Null.NullBoolean); - } - - [Test] - [TestCase("BadKey1")] - [TestCase("AAAAAAA")] - public void HostController_GetBoolean_InvalidKey_Returns_Default_Value(string key) - { - Assert.AreEqual(HostController.Instance.GetBoolean(key, true), true); - Assert.AreEqual(HostController.Instance.GetBoolean(key, false), false); - } - - [Test] - [TestCase("")] - [TestCase(null)] - [ExpectedException(typeof(ArgumentException))] - public void HostController_GetBoolean_NullEmpty(string key) - { - HostController.Instance.GetBoolean(key); - } - - [Test] - [TestCase("Double_7_S")] - [TestCase("Double_8_U")] - public void HostController_GetDouble_If_Key_Exists(string key) - { - double s = HostController.Instance.GetDouble(key); - Assert.AreEqual(s.ToString(), this.GetValue(key)); - Assert.AreEqual(HostController.Instance.GetDouble(key, 54.54).ToString(), this.GetValue(key)); - } - - [Test] - [TestCase("BadKey1")] - [TestCase("AAAAAAA")] - public void HostController_GetDouble_InvalidKey_Returns_Null_Value(string key) - { - Assert.AreEqual(HostController.Instance.GetDouble(key), Null.NullDouble); - } - - [Test] - [TestCase("BadKey1")] - [TestCase("AAAAAAA")] - public void HostController_GetDouble_InvalidKey_Returns_Default_Value(string key) - { - Assert.AreEqual(HostController.Instance.GetDouble(key, 21.58), 21.58); - } - - [Test] - [TestCase("")] - [TestCase(null)] - [ExpectedException(typeof(ArgumentException))] - public void HostController_GetDouble_NullEmpty(string key) - { - HostController.Instance.GetDouble(key); - } - - private string GetValue(string key) - { - return this._hostSettingsTable.Rows.Find(key)["SettingValue"].ToString(); - } - } -} + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + this._mockCache = MockComponentProvider.CreateDataCacheProvider(); + MockComponentProvider.CreateEventLogController(); + + this._hostSettingsTable = new DataTable("HostSettings"); + + var nameCol = this._hostSettingsTable.Columns.Add("SettingName"); + this._hostSettingsTable.Columns.Add("SettingValue"); + this._hostSettingsTable.Columns.Add("SettingIsSecure"); + this._hostSettingsTable.PrimaryKey = new[] { nameCol }; + + this._hostSettingsTable.Rows.Add("String_1_S", "String_1_S", true); + this._hostSettingsTable.Rows.Add("String_2_S", "String_1_S", true); + this._hostSettingsTable.Rows.Add("String_3_U", "Value_3_U", false); + this._hostSettingsTable.Rows.Add("String_4_U", "Value_4_U", false); + this._hostSettingsTable.Rows.Add("Int_5_U", "5", false); + this._hostSettingsTable.Rows.Add("Int_6_S", "6", true); + this._hostSettingsTable.Rows.Add("Double_7_S", "7", true); + this._hostSettingsTable.Rows.Add("Double_8_U", "8", false); + this._hostSettingsTable.Rows.Add("Bool_9_U", false, false); + this._hostSettingsTable.Rows.Add("Bool_10_S", false, true); + + this._mockData = MockComponentProvider.CreateDataProvider(); + this._mockData.Setup(c => c.GetHostSettings()).Returns(this._hostSettingsTable.CreateDataReader()); + this._mockData.Setup(c => c.GetProviderPath()).Returns(string.Empty); + + DataCache.ClearCache(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + MockComponentProvider.ResetContainer(); + } + + [Test] + public void HostController_GetSettings_GetList() + { + // Arrange + var expectedDic = new Dictionary(); + + foreach (DataRow row in this._hostSettingsTable.Rows) + { + var conf = new ConfigurationSetting(); + conf.Key = row["SettingName"].ToString(); + conf.Value = row["SettingValue"].ToString(); + bool IsSecure; + bool.TryParse(row["SettingIsSecure"].ToString(), out IsSecure); + conf.IsSecure = IsSecure; + expectedDic.Add(conf.Key, conf); + } + + // Act + var settingsDic = HostController.Instance.GetSettings(); + + // Assert + foreach (var currentConfig in settingsDic) + { + Assert.AreEqual(currentConfig.Key, currentConfig.Value.Key); + Assert.AreEqual(expectedDic[currentConfig.Key].Value, currentConfig.Value.Value); + Assert.AreEqual(expectedDic[currentConfig.Key].IsSecure, currentConfig.Value.IsSecure); + } + } + + [Test] + public void HostController_GetSettingsDictionary_GetList() + { + // Arrange + // Convert table to Dictionary + var expectedDic = this._hostSettingsTable.Rows.Cast().ToDictionary(row => row["SettingName"].ToString(), row => row["SettingValue"].ToString()); + + // Act + var settingsDic = HostController.Instance.GetSettingsDictionary(); + + // Assert + CollectionAssert.AreEquivalent(expectedDic.Values, settingsDic.Values); + } + + [Test] + public void HostController_Update_ExistingValue() + { + // Arrange + const string key = "String_1_S"; + const string value = "MyValue"; + this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); + + // Act + HostController.Instance.Update(key, value); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); + } + + [Test] + public void HostController_Update_ExistingValue_ResetCache() + { + // Arrange + const string key = "String_1_S"; + const string value = "MyValue"; + this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); + + // Act + HostController.Instance.Update(key, value); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); + } + + [Test] + public void HostController_Update_ExistingValue_ResetCache_With_Overload() + { + // Arrange + const string key = "String_1_S"; + const string value = "MyValue"; + this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); + + // Act + HostController.Instance.Update(key, value, true); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); + } + + [Test] + public void HostController_Update_ExistingValue_Dont_Reset_Cache() + { + // Arrange + const string key = "String_1_S"; + const string value = "MyValue"; + this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); + + // Act + HostController.Instance.Update(key, value, false); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + + // Clear was not called a second time + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); + } + + [Test] + public void HostController_Update_Dictionary() + { + // Arrange + var settings = new Dictionary + { + { "String_1_S", "MyValue" }, + }; + + // Act + HostController.Instance.Update(settings); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting("String_1_S", "MyValue", false, It.IsAny()), Times.Exactly(1)); + this._mockCache.Verify(c => c.Clear("Host", string.Empty), Times.Exactly(1)); + } + + [Test] + public void HostController_Update_NewValue() + { + // Arrange + const string key = "MyKey"; + const string value = "MyValue"; + this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); + + // Act + HostController.Instance.Update(key, value); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); + } + + [Test] + public void HostController_Update_NewValue_ResetCache_With_Overload() + { + // Arrange + const string key = "MyKey"; + const string value = "MyValue"; + this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); + + // Act + HostController.Instance.Update(key, value, true); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); + } + + [Test] + public void HostController_Update_NewValue_ResetCache() + { + // Arrange + const string key = "MyKey"; + const string value = "MyValue"; + this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); + + // Act + HostController.Instance.Update(key, value); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); + } + + [Test] + public void HostController_Update_NewValue_Dont_Reset_Cache() + { + // Arrange + const string key = "MyKey"; + const string value = "MyValue"; + this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); + + // Act + HostController.Instance.Update(key, value, false); + + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); + } + + [Test] + [TestCase("String_1_S")] + [TestCase("String_2_S")] + [TestCase("String_3_U")] + [TestCase("String_4_U")] + public void HostController_GetString_If_Key_Exists(string key) + { + Assert.AreEqual(HostController.Instance.GetString(key), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetString(key, "Hello Default"), this.GetValue(key)); + } + + [Test] + [TestCase("BadKey1")] + [TestCase("AAAAAAA")] + public void HostController_GetString_InvalidKey_Returns_Null_Value(string key) + { + Assert.AreEqual(HostController.Instance.GetString(key), Null.NullString); + } + + [Test] + [TestCase("BadKey1")] + [TestCase("AAAAAAA")] + public void HostController_GetString_InvalidKey_Returns_Default_Value(string key) + { + Assert.AreEqual(HostController.Instance.GetString(key, "Hello Default"), "Hello Default"); + } + + [Test] + [TestCase("")] + [TestCase(null)] + [ExpectedException(typeof(ArgumentException))] + public void HostController_GetString_NullEmpty(string key) + { + HostController.Instance.GetString(key); + } + + [Test] + [TestCase("Int_5_U")] + [TestCase("Int_6_S")] + public void HostController_GetInteger_If_Key_Exists(string key) + { + int s = HostController.Instance.GetInteger(key); + Assert.AreEqual(s.ToString(), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetInteger(key, 12).ToString(), this.GetValue(key)); + } + + [Test] + [TestCase("BadKey1")] + [TestCase("AAAAAAA")] + public void HostController_GetInteger_InvalidKey_Returns_Null_Value(string key) + { + Assert.AreEqual(HostController.Instance.GetInteger(key), Null.NullInteger); + } + + [Test] + [TestCase("BadKey1")] + [TestCase("AAAAAAA")] + public void HostController_GetInteger_InvalidKey_Returns_Default_Value(string key) + { + Assert.AreEqual(HostController.Instance.GetInteger(key, 6969), 6969); + } + + [Test] + [TestCase("")] + [TestCase(null)] + [ExpectedException(typeof(ArgumentException))] + public void HostController_GetInteger_NullEmpty(string key) + { + HostController.Instance.GetInteger(key); + } + + [Test] + [TestCase("Bool_9_U")] + [TestCase("Bool_10_S")] + public void HostController_GetBoolean_If_Key_Exists(string key) + { + Assert.AreEqual(HostController.Instance.GetBoolean(key).ToString(), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetBoolean(key, false).ToString(), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetBoolean(key, true).ToString(), this.GetValue(key)); + } + + [Test] + [TestCase("BadKey1")] + [TestCase("AAAAAAA")] + public void HostController_GetBoolean_InvalidKey_Returns_Null_Value(string key) + { + Assert.AreEqual(HostController.Instance.GetBoolean(key), Null.NullBoolean); + } + + [Test] + [TestCase("BadKey1")] + [TestCase("AAAAAAA")] + public void HostController_GetBoolean_InvalidKey_Returns_Default_Value(string key) + { + Assert.AreEqual(HostController.Instance.GetBoolean(key, true), true); + Assert.AreEqual(HostController.Instance.GetBoolean(key, false), false); + } + + [Test] + [TestCase("")] + [TestCase(null)] + [ExpectedException(typeof(ArgumentException))] + public void HostController_GetBoolean_NullEmpty(string key) + { + HostController.Instance.GetBoolean(key); + } + + [Test] + [TestCase("Double_7_S")] + [TestCase("Double_8_U")] + public void HostController_GetDouble_If_Key_Exists(string key) + { + double s = HostController.Instance.GetDouble(key); + Assert.AreEqual(s.ToString(), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetDouble(key, 54.54).ToString(), this.GetValue(key)); + } + + [Test] + [TestCase("BadKey1")] + [TestCase("AAAAAAA")] + public void HostController_GetDouble_InvalidKey_Returns_Null_Value(string key) + { + Assert.AreEqual(HostController.Instance.GetDouble(key), Null.NullDouble); + } + + [Test] + [TestCase("BadKey1")] + [TestCase("AAAAAAA")] + public void HostController_GetDouble_InvalidKey_Returns_Default_Value(string key) + { + Assert.AreEqual(HostController.Instance.GetDouble(key, 21.58), 21.58); + } + + [Test] + [TestCase("")] + [TestCase(null)] + [ExpectedException(typeof(ArgumentException))] + public void HostController_GetDouble_NullEmpty(string key) + { + HostController.Instance.GetDouble(key); + } + + private string GetValue(string key) + { + return this._hostSettingsTable.Rows.Find(key)["SettingValue"].ToString(); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs index 2f9341d0b38..f8138cbb0b1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs @@ -2,1316 +2,1318 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -// ReSharper disable InconsistentNaming -namespace DotNetNuke.Tests.Core.Controllers.Messaging -{ - using System; - using System.Collections.Generic; - using System.Data; - using System.Globalization; +// ReSharper disable InconsistentNaming +namespace DotNetNuke.Tests.Core.Controllers.Messaging +{ + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; using System.Text; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.ComponentModel; - using DotNetNuke.Data; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Users; - using DotNetNuke.Security.Roles; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.Social.Messaging; - using DotNetNuke.Services.Social.Messaging.Exceptions; - using DotNetNuke.Services.Social.Messaging.Internal; - using DotNetNuke.Services.Social.Notifications; - using DotNetNuke.Services.Social.Notifications.Data; - using DotNetNuke.Tests.Utilities; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Services.Social.Notifications.Data; + using DotNetNuke.Tests.Utilities; using DotNetNuke.Tests.Utilities.Mocks; using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using NUnit.Framework; - - [TestFixture] - public class NotificationsControllerTests - { - private Mock _mockDataService; - private Mock _portalController; - private Mock _portalGroupController; - private Mock _mockMessagingDataService; - private Mock _mockMessagingController; - private Mock _mockInternalMessagingController; - private NotificationsController _notificationsController; - private Mock _mockNotificationsController; - private Mock _dataProvider; - private Mock _cachingProvider; - private DataTable _dtNotificationTypes; - private DataTable _dtNotificationTypeActions; - private DataTable _dtNotificationActions; - - [SetUp] - public void SetUp() - { - var serviceCollection = new ServiceCollection(); + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class NotificationsControllerTests + { + private Mock _mockDataService; + private Mock _portalController; + private Mock _portalGroupController; + private Mock _mockMessagingDataService; + private Mock _mockMessagingController; + private Mock _mockInternalMessagingController; + private NotificationsController _notificationsController; + private Mock _mockNotificationsController; + private Mock _dataProvider; + private Mock _cachingProvider; + private DataTable _dtNotificationTypes; + private DataTable _dtNotificationTypeActions; + private DataTable _dtNotificationActions; + + [SetUp] + public void SetUp() + { + var serviceCollection = new ServiceCollection(); var mockApplicationStatusInfo = new Mock(); mockApplicationStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.Install); serviceCollection.AddTransient(container => mockApplicationStatusInfo.Object); serviceCollection.AddTransient(container => Mock.Of()); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - ComponentFactory.Container = new SimpleContainer(); - - this._mockDataService = new Mock(); - this._portalController = new Mock(); - this._portalGroupController = new Mock(); - - this._mockMessagingDataService = new Mock(); - this._dataProvider = MockComponentProvider.CreateDataProvider(); - this._cachingProvider = MockComponentProvider.CreateDataCacheProvider(); - - this._notificationsController = new NotificationsController(this._mockDataService.Object, this._mockMessagingDataService.Object); - this._mockNotificationsController = new Mock { CallBase = true }; - - this._mockMessagingController = new Mock(); - MessagingController.SetTestableInstance(this._mockMessagingController.Object); - PortalController.SetTestableInstance(this._portalController.Object); - PortalGroupController.RegisterInstance(this._portalGroupController.Object); - - this._mockInternalMessagingController = new Mock(); - InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); - - DataService.RegisterInstance(this._mockDataService.Object); - DotNetNuke.Services.Social.Messaging.Data.DataService.RegisterInstance(this._mockMessagingDataService.Object); - - this.SetupDataProvider(); - this.SetupDataTables(); - } - - [TearDown] - public void TearDown() - { - Globals.DependencyProvider = null; - ComponentFactory.Container = null; - MessagingController.ClearInstance(); - PortalController.ClearInstance(); - InternalMessagingController.ClearInstance(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void CreateNotificationType_Throws_On_Null_NotificationType() - { - this._notificationsController.CreateNotificationType(null); - } - - [Test] - [TestCase("")] - [TestCase(null)] - [ExpectedException(typeof(ArgumentException))] - public void CreateNotificationType_Throws_On_Null_Or_Empty_Name(string name) - { - var notificationType = CreateNewNotificationType(); - notificationType.Name = name; - - this._notificationsController.CreateNotificationType(notificationType); - } - - [Test] - public void CreateNotificationType_Calls_DataService_CreateNotificationType() - { - this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - - this._mockDataService - .Setup(ds => ds.CreateNotificationType(Constants.Messaging_NotificationTypeName, It.IsAny(), It.IsAny(), It.IsAny(), Constants.UserID_User12, It.IsAny())) - .Verifiable(); - - this._mockNotificationsController.Object.CreateNotificationType(CreateNewNotificationType()); - - this._mockDataService.Verify(); - } - - [Test] - [TestCase(int.MaxValue, int.MaxValue)] - [TestCase(1, 1)] - [TestCase(0, 0)] - public void CreateNotificationType_Returns_Object_With_Valid_TimeToLive(int actualTimeToLiveTotalMinutes, int expectedTimeToLiveTotalMinutes) - { - var actualTimeToLive = TimeSpan.FromMinutes(actualTimeToLiveTotalMinutes); - - var notificationType = CreateNewNotificationType(); - notificationType.TimeToLive = actualTimeToLive; - this._notificationsController.CreateNotificationType(notificationType); - - Assert.AreEqual(expectedTimeToLiveTotalMinutes, (int)notificationType.TimeToLive.TotalMinutes); - } - - [Test] - public void CreateNotificationType_Makes_Valid_Object() - { - var expectedNotificationType = CreateValidNotificationType(); - - this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - - this._mockDataService - .Setup(ds => ds.CreateNotificationType( - expectedNotificationType.Name, - expectedNotificationType.Description, - (int)expectedNotificationType.TimeToLive.TotalMinutes, - expectedNotificationType.DesktopModuleId, - Constants.UserID_User12, false)) - .Returns(Constants.Messaging_NotificationTypeId); - - var actualNotificationType = CreateNewNotificationType(); - this._mockNotificationsController.Object.CreateNotificationType(actualNotificationType); - - Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); - } - - [Test] - public void DeleteNotificationType_Calls_DataService_DeleteNotificationType() - { - this._mockDataService.Setup(ds => ds.DeleteNotificationType(Constants.Messaging_NotificationTypeId)).Verifiable(); - this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()); - this._mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); - this._mockDataService.Verify(); - } - - [Test] - public void DeleteNotificationType_Removes_Cache_Object() - { - this._mockDataService.Setup(ds => ds.DeleteNotificationType(Constants.Messaging_NotificationTypeId)); - this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()).Verifiable(); - this._mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); - this._mockNotificationsController.Verify(); - } - - [Test] - public void GetNotificationType_By_Id_Gets_Object_From_Cache() - { - this._cachingProvider.Object.PurgeCache(); - this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); - this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); - this._cachingProvider.Verify(); - } - - [Test] - public void GetNotificationType_By_Id_Calls_DataService_GetNotificationType_When_Object_Is_Not_In_Cache() - { - this._cachingProvider.Object.PurgeCache(); - - var messageTypeDataTable = new DataTable(); - - this._mockDataService - .Setup(ds => ds.GetNotificationType(Constants.Messaging_NotificationTypeId)) - .Returns(messageTypeDataTable.CreateDataReader()) - .Verifiable(); - - this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); - - this._mockDataService.Verify(); - } - - [Test] - public void GetNotificationType_By_Id_Returns_Valid_Object() - { - this._cachingProvider.Object.PurgeCache(); - - var expectedNotificationType = CreateValidNotificationType(); - - this._dtNotificationTypes.Rows.Clear(); - - this._dtNotificationTypes.Rows.Add( - expectedNotificationType.NotificationTypeId, - expectedNotificationType.Name, - expectedNotificationType.Description, - (int)expectedNotificationType.TimeToLive.TotalMinutes, - expectedNotificationType.DesktopModuleId); - - this._mockDataService - .Setup(ds => ds.GetNotificationType(Constants.Messaging_NotificationTypeId)) - .Returns(this._dtNotificationTypes.CreateDataReader()); - - var actualNotificationType = this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); - - Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void GetNotificationType_By_Name_Throws_On_Null_Or_Empty_Name(string name) - { - this._notificationsController.GetNotificationType(name); - } - - [Test] - public void GetNotificationType_By_Name_Gets_Object_From_Cache() - { - this._cachingProvider.Object.PurgeCache(); - this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); - this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); - this._cachingProvider.Verify(); - } - - [Test] - public void GetNotificationType_By_Name_Calls_DataService_GetNotificationTypeByName_When_Object_Is_Not_In_Cache() - { - this._cachingProvider.Object.PurgeCache(); - - this._mockDataService - .Setup(ds => ds.GetNotificationTypeByName(Constants.Messaging_NotificationTypeName)) - .Returns(this._dtNotificationTypes.CreateDataReader()) - .Verifiable(); - - this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); - - this._mockDataService.Verify(); - } - - [Test] - public void GetNotificationType_By_Name_Returns_Valid_Object() - { - this._cachingProvider.Object.PurgeCache(); - - var expectedNotificationType = CreateValidNotificationType(); - - this._dtNotificationTypes.Rows.Clear(); - - this._dtNotificationTypes.Rows.Add( - expectedNotificationType.NotificationTypeId, - expectedNotificationType.Name, - expectedNotificationType.Description, - (int)expectedNotificationType.TimeToLive.TotalMinutes, - expectedNotificationType.DesktopModuleId); - - this._mockDataService - .Setup(ds => ds.GetNotificationTypeByName(Constants.Messaging_NotificationTypeName)) - .Returns(this._dtNotificationTypes.CreateDataReader()); - - var actualNotificationType = this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); - - Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void SetNotificationTypeActions_Throws_On_Null() - { - this._notificationsController.SetNotificationTypeActions(null, Constants.Messaging_NotificationTypeId); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SetNotificationTypeActions_Throws_On_EmptyList() - { - this._notificationsController.SetNotificationTypeActions(new List(), Constants.Messaging_NotificationTypeId); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void SetNotificationTypeActions_Throws_On_Null_Or_Empty_Name(string name) - { - var action = CreateNewNotificationTypeAction(); - action.NameResourceKey = name; - this._notificationsController.SetNotificationTypeActions(new[] { action }, Constants.Messaging_NotificationTypeId); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void SetNotificationTypeActions_Throws_On_Null_Or_Empty_APICall(string apiCall) - { - var action = CreateNewNotificationTypeAction(); - action.APICall = apiCall; - this._notificationsController.SetNotificationTypeActions(new[] { action }, Constants.Messaging_NotificationTypeId); - } - - [Test] - public void SetNotificationTypeActions_Calls_DataService_AddNotificationTypeAction_For_Each_Of_Two_Actions() - { - this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - - // _mockDataService - // .Setup(ds => ds.AddNotificationTypeAction( - // Constants.Messaging_NotificationTypeId, - // Constants.Messaging_NotificationTypeActionNameResourceKey, - // Constants.Messaging_NotificationTypeActionDescriptionResourceKey, - // Constants.Messaging_NotificationTypeActionConfirmResourceKey, - // Constants.Messaging_NotificationTypeActionAPICall, - // Constants.UserID_User12)) - // .Verifiable(); - this._mockNotificationsController.Setup(nc => nc.GetNotificationTypeAction(It.IsAny())); - - this._mockNotificationsController.Object.SetNotificationTypeActions( - new[] { CreateNewNotificationTypeAction(), CreateNewNotificationTypeAction() }, - Constants.Messaging_NotificationTypeId); - - this._mockDataService.Verify( - x => x.AddNotificationTypeAction( - Constants.Messaging_NotificationTypeId, - Constants.Messaging_NotificationTypeActionNameResourceKey, - Constants.Messaging_NotificationTypeActionDescriptionResourceKey, - Constants.Messaging_NotificationTypeActionConfirmResourceKey, - Constants.Messaging_NotificationTypeActionAPICall, - Constants.UserID_User12), Times.Exactly(2)); - } - - [Test] - public void SetNotificationTypeActions_Sets_NotificationTypeActionId_And_NotificationTypeId() - { - var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); - - this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - - this._mockDataService - .Setup(ds => ds.AddNotificationTypeAction( - expectedNotificationTypeAction.NotificationTypeId, - expectedNotificationTypeAction.NameResourceKey, - expectedNotificationTypeAction.DescriptionResourceKey, - expectedNotificationTypeAction.ConfirmResourceKey, - expectedNotificationTypeAction.APICall, - Constants.UserID_User12)) - .Returns(expectedNotificationTypeAction.NotificationTypeActionId); - - this._mockNotificationsController - .Setup(nc => nc.GetNotificationTypeAction(expectedNotificationTypeAction.NotificationTypeActionId)) - .Returns(expectedNotificationTypeAction); - - var action = CreateNewNotificationTypeAction(); - this._mockNotificationsController.Object.SetNotificationTypeActions(new[] { action }, expectedNotificationTypeAction.NotificationTypeId); - - Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, action)); - } - - [Test] - public void DeleteNotificationTypeAction_Calls_DataService_DeleteNotificationTypeAction() - { - this._mockDataService.Setup(ds => ds.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)).Verifiable(); - this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()); - this._mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - this._mockDataService.Verify(); - } - - [Test] - public void DeleteNotificationTypeAction_Removes_Cache_Object() - { - this._mockDataService.Setup(ds => ds.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)); - this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()).Verifiable(); - this._mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - this._mockNotificationsController.Verify(); - } - - [Test] - public void GetNotificationTypeAction_By_Id_Gets_Object_From_Cache() - { - this._cachingProvider.Object.PurgeCache(); - this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); - this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - this._cachingProvider.Verify(); - } - - [Test] - public void GetNotificationTypeAction_By_Id_Calls_DataService_GetNotificationTypeAction_When_Object_Is_Not_In_Cache() - { - this._cachingProvider.Object.PurgeCache(); - - this._mockDataService - .Setup(ds => ds.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)) - .Returns(this._dtNotificationTypeActions.CreateDataReader()) - .Verifiable(); - - this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - - this._mockDataService.Verify(); - } - - [Test] - public void GetNotificationTypeAction_By_Id_Returns_Valid_Object() - { - this._cachingProvider.Object.PurgeCache(); - - var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); - - this._dtNotificationTypeActions.Clear(); - - this._dtNotificationTypeActions.Rows.Add( - expectedNotificationTypeAction.NotificationTypeActionId, - expectedNotificationTypeAction.NotificationTypeId, - expectedNotificationTypeAction.NameResourceKey, - expectedNotificationTypeAction.DescriptionResourceKey, - expectedNotificationTypeAction.ConfirmResourceKey, - expectedNotificationTypeAction.Order, - expectedNotificationTypeAction.APICall); - - this._mockDataService - .Setup(ds => ds.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)) - .Returns(this._dtNotificationTypeActions.CreateDataReader); - - var actualNotificationTypeAction = this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - - Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeAction)); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void GetNotificationTypeAction_By_Name_Throws_On_Null_Or_Empty_Name(string name) - { - this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, name); - } - - [Test] - public void GetNotificationTypeAction_By_Name_Gets_Object_From_Cache() - { - this._cachingProvider.Object.PurgeCache(); - this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); - this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); - this._cachingProvider.Verify(); - } - - [Test] - public void GetNotificationTypeAction_By_Name_Calls_DataService_GetNotificationTypeActionByName_When_Object_Is_Not_In_Cache() - { - this._cachingProvider.Object.PurgeCache(); - - this._mockDataService - .Setup(ds => ds.GetNotificationTypeActionByName( - Constants.Messaging_NotificationTypeId, - Constants.Messaging_NotificationTypeActionNameResourceKey)) - .Returns(this._dtNotificationTypeActions.CreateDataReader()) - .Verifiable(); - - this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); - - this._mockDataService.Verify(); - } - - [Test] - public void GetNotificationTypeAction_By_Name_Returns_Valid_Object() - { - this._cachingProvider.Object.PurgeCache(); - - var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); - - this._dtNotificationTypeActions.Clear(); - - this._dtNotificationTypeActions.Rows.Add( - expectedNotificationTypeAction.NotificationTypeActionId, - expectedNotificationTypeAction.NotificationTypeId, - expectedNotificationTypeAction.NameResourceKey, - expectedNotificationTypeAction.DescriptionResourceKey, - expectedNotificationTypeAction.ConfirmResourceKey, - expectedNotificationTypeAction.Order, - expectedNotificationTypeAction.APICall); - - this._mockDataService - .Setup(ds => ds.GetNotificationTypeActionByName( - Constants.Messaging_NotificationTypeId, - Constants.Messaging_NotificationTypeActionNameResourceKey)) - .Returns(this._dtNotificationTypeActions.CreateDataReader()); - - var actualNotificationTypeAction = this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); - - Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeAction)); - } - - [Test] - public void GetNotificationTypeActions_Calls_DataService_GetNotificationTypeActions() - { - this._mockDataService - .Setup(ds => ds.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId)) - .Returns(this._dtNotificationTypeActions.CreateDataReader()) - .Verifiable(); - - this._notificationsController.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId); - - this._mockDataService.Verify(); - } - - [Test] - public void GetNotificationTypeActions_Returns_Valid_Object() - { - var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); - - this._dtNotificationTypeActions.Clear(); - - this._dtNotificationTypeActions.Rows.Add( - expectedNotificationTypeAction.NotificationTypeActionId, - expectedNotificationTypeAction.NotificationTypeId, - expectedNotificationTypeAction.NameResourceKey, - expectedNotificationTypeAction.DescriptionResourceKey, - expectedNotificationTypeAction.ConfirmResourceKey, - expectedNotificationTypeAction.Order, - expectedNotificationTypeAction.APICall); - - this._mockDataService.Setup(ds => ds.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId)).Returns(this._dtNotificationTypeActions.CreateDataReader()); - - var actualNotificationTypeActions = this._notificationsController.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId); - - Assert.AreEqual(1, actualNotificationTypeActions.Count); - Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeActions[0])); - } - - [Test] - public void SendNotification_Sets_Empty_SenderUserId_With_Admin() - { - var adminUser = new UserInfo - { - UserID = Constants.UserID_Admin, - DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.CONTENT_ValidPortalId, - }; - - this._mockNotificationsController.Setup(nc => nc.GetAdminUser()).Returns(adminUser); - - this._mockNotificationsController - .Setup(nc => nc.SendNotification( - It.IsAny(), - Constants.PORTAL_Zero, - It.IsAny>(), - It.IsAny>())); - - var notification = CreateUnsavedNotification(); - - this._mockNotificationsController.Object.SendNotification( - notification, - Constants.PORTAL_Zero, - new List(), - new List()); - - Assert.AreEqual(adminUser.UserID, notification.SenderUserID); - } - - [Test] - [TestCase(null, null)] - [TestCase(null, "")] - [TestCase("", null)] - [TestCase("", "")] - [ExpectedException(typeof(ArgumentException))] - public void SendNotification_Throws_On_Null_Or_Empty_Subject_And_Body(string subject, string body) - { - var notification = CreateUnsavedNotification(); - notification.Subject = subject; - notification.Body = body; - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - this._notificationsController.SendNotification( - notification, - Constants.PORTAL_Zero, - new List(), - new List()); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SendNotification_Throws_On_Null_Roles_And_Users() - { - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - this._notificationsController.SendNotification( - CreateUnsavedNotification(), - Constants.PORTAL_Zero, - null, - null); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SendNotification_Throws_On_Large_Subject() - { - var notification = CreateUnsavedNotification(); - var subject = new StringBuilder(); - for (var i = 0; i <= 40; i++) - { - subject.Append("1234567890"); - } - - notification.Subject = subject.ToString(); - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - this._notificationsController.SendNotification( - notification, - Constants.PORTAL_Zero, - new List(), - new List()); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SendNotification_Throws_On_Roles_And_Users_With_No_DisplayNames() - { - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - this._notificationsController.SendNotification( - CreateUnsavedNotification(), - Constants.PORTAL_Zero, - new List(), - new List()); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SendNotification_Throws_On_Large_To_List() - { - var roles = new List(); - var users = new List(); - - for (var i = 0; i <= 100; i++) - { - roles.Add(new RoleInfo { RoleName = "1234567890" }); - users.Add(new UserInfo { DisplayName = "1234567890" }); - } - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - this._notificationsController.SendNotification( - CreateUnsavedNotification(), - Constants.PORTAL_Zero, - roles, - users); - } - - [Test] - public void SendNotification_Calls_DataService_On_Valid_Notification() - { - var adminUser = new UserInfo - { - UserID = Constants.UserID_Admin, - DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero, - }; - - this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - var roles = new List(); - var users = new List - { - new UserInfo - { - UserID = Constants.UserID_User12, - DisplayName = Constants.UserDisplayName_User12 - }, - }; - - this._mockDataService - .Setup(ds => ds.SendNotification( - It.IsAny(), - Constants.PORTAL_Zero)) - .Verifiable(); - - this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); - - var notification = CreateUnsavedNotification(); - notification.SenderUserID = adminUser.UserID; - notification.SendToast = false; - - this._mockNotificationsController.Object.SendNotification( - notification, - Constants.PORTAL_Zero, - roles, - users); - - this._mockDataService.Verify(); - } - - [Test] - public void SendNotification_Calls_DataService_On_Valid_Notification_When_Portal_Is_In_Group() - { - var adminUser = new UserInfo - { - UserID = Constants.UserID_Admin, - DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero, - }; - - this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); - this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); - - var roles = new List(); - var users = new List - { - new UserInfo - { - UserID = Constants.UserID_User12, - DisplayName = Constants.UserDisplayName_User12 - }, - }; - - this._mockDataService - .Setup(ds => ds.SendNotification( - It.IsAny(), - Constants.PORTAL_Zero)) - .Verifiable(); - - this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); - - var notification = CreateUnsavedNotification(); - notification.SenderUserID = adminUser.UserID; - notification.SendToast = false; - - this._mockNotificationsController.Object.SendNotification( - notification, - Constants.PORTAL_Zero, - roles, - users); - - this._mockDataService.Verify(); - } - - [Test] - public void SendNotification_Calls_Messaging_DataService_CreateSocialMessageRecipientsForRole_When_Passing_Roles() - { - var adminUser = new UserInfo - { - UserID = Constants.UserID_Admin, - DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero, - }; - - this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - var roles = new List - { - new RoleInfo - { - RoleID = Constants.RoleID_RegisteredUsers, - RoleName = Constants.RoleName_RegisteredUsers - }, - }; - var users = new List(); - - this._mockDataService - .Setup(ds => ds.SendNotification( - It.IsAny(), - Constants.PORTAL_Zero)) - .Returns(Constants.Messaging_MessageId_1); - - this._mockMessagingDataService - .Setup(mds => mds.CreateMessageRecipientsForRole( - Constants.Messaging_MessageId_1, - Constants.RoleID_RegisteredUsers.ToString(CultureInfo.InvariantCulture), - It.IsAny())) - .Verifiable(); - - this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); - - var notification = CreateUnsavedNotification(); - notification.SenderUserID = adminUser.UserID; - notification.SendToast = false; - - this._mockNotificationsController.Object.SendNotification( - notification, - Constants.PORTAL_Zero, - roles, - users); - - this._mockMessagingDataService.Verify(); - } - - [Test] - public void SendNotification_Calls_Messaging_DataService_SaveSocialMessageRecipient_When_Passing_Users() - { - var adminUser = new UserInfo - { - UserID = Constants.UserID_Admin, - DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero, - }; - - this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - var roles = new List(); - var users = new List - { - new UserInfo - { - UserID = Constants.UserID_User12, - DisplayName = Constants.UserDisplayName_User12 - }, - }; - - this._mockDataService - .Setup(ds => ds.SendNotification( - It.IsAny(), - Constants.PORTAL_Zero)) - .Returns(Constants.Messaging_MessageId_1); - - this._mockInternalMessagingController - .Setup(mc => mc.GetMessageRecipient( - Constants.Messaging_MessageId_1, - Constants.UserID_User12)) - .Returns((MessageRecipient)null); - - this._mockMessagingDataService - .Setup(mds => mds.SaveMessageRecipient( - It.Is(mr => - mr.MessageID == Constants.Messaging_MessageId_1 && - mr.UserID == Constants.UserID_User12 && - mr.Read == false && - mr.RecipientID == Null.NullInteger), - It.IsAny())) - .Verifiable(); - - this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); - - var notification = CreateUnsavedNotification(); - notification.SenderUserID = adminUser.UserID; - notification.SendToast = false; - - this._mockNotificationsController.Object.SendNotification( - notification, - Constants.PORTAL_Zero, - roles, - users); - - this._mockMessagingDataService.Verify(); - } - - [Test] - public void SendNotification_Returns_Valid_Object() - { - var expectedNotification = CreateValidNotification(); - - var adminUser = new UserInfo - { - UserID = Constants.UserID_Admin, - DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero, - }; - - this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - var roles = new List(); - var users = new List - { - new UserInfo - { - UserID = Constants.UserID_User12, - DisplayName = Constants.UserDisplayName_User12 - }, - }; - - this._mockDataService - .Setup(ds => ds.SendNotification( - It.IsAny(), - Constants.PORTAL_Zero)) - .Returns(Constants.Messaging_MessageId_1); - - this._mockMessagingDataService - .Setup(mds => mds.CreateMessageRecipientsForRole( - Constants.Messaging_MessageId_1, - Constants.RoleID_RegisteredUsers.ToString(CultureInfo.InvariantCulture), - It.IsAny())); - - this._mockInternalMessagingController - .Setup(mc => mc.GetMessageRecipient( - Constants.Messaging_MessageId_1, - Constants.UserID_User12)) - .Returns((MessageRecipient)null); - - this._mockMessagingDataService - .Setup(mds => mds.SaveMessageRecipient( - It.Is(mr => - mr.MessageID == Constants.Messaging_MessageId_1 && - mr.UserID == Constants.UserID_User12 && - mr.Read == false && - mr.RecipientID == Null.NullInteger), - It.IsAny())); - - this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); - - var notification = CreateUnsavedNotification(); - notification.SenderUserID = adminUser.UserID; - notification.SendToast = false; - - this._mockNotificationsController.Object.SendNotification( - notification, - Constants.PORTAL_Zero, - roles, - users); - - Assert.IsTrue(new NotificationComparer().Equals(expectedNotification, notification)); - } - - [Test] - public void DeleteNotification_Calls_DataService_DeleteNotification() - { - var messageRecipients = new List - { - new MessageRecipient(), - }; - - this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(messageRecipients); - - this._mockDataService.Setup(ds => ds.DeleteNotification(Constants.Messaging_MessageId_1)).Verifiable(); - this._notificationsController.DeleteNotification(Constants.Messaging_MessageId_1); - this._mockDataService.Verify(); - } - - [Test] - public void GetNotifications_Calls_DataService_GetNotifications() - { - this._mockDataService - .Setup(ds => ds.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, It.IsAny(), It.IsAny())) - .Returns(new DataTable().CreateDataReader()) - .Verifiable(); - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - this._notificationsController.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, 0, 10); - this._mockDataService.Verify(); - } - - [Test] - public void GetNotifications_Calls_DataService_GetNotifications_When_Portal_Is_In_Group() - { - this._mockDataService - .Setup(ds => ds.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, It.IsAny(), It.IsAny())) - .Returns(new DataTable().CreateDataReader()) - .Verifiable(); - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); - this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); - - this._notificationsController.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, 0, 10); - this._mockDataService.Verify(); - } - - [Test] - public void GetNotifications_Calls_DataService_GetNotificationByContext() - { - this._mockDataService - .Setup(ds => ds.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext)) - .Returns(new DataTable().CreateDataReader()) - .Verifiable(); - - this._notificationsController.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext); - this._mockDataService.Verify(); - } - - [Test] - public void CountNotifications_Calls_DataService_CountNotifications() - { - this._mockDataService.Setup(ds => ds.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero)).Verifiable(); - this._notificationsController.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero); - this._mockDataService.Verify(); - } - - [Test] - public void DeleteNotificationRecipient_Calls_MessagingController_DeleteMessageRecipient() - { - this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); - this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); - this._notificationsController.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); - this._mockMessagingController.Verify(); - } - - [Test] - public void DeleteNotificationRecipientByContext_Calls_DeleteMessageRecipient() - { - this._mockNotificationsController.Setup(mc => mc.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); - this._mockNotificationsController.Setup(mc => mc.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext)) - .Returns(new List { new Notification { NotificationID = Constants.Messaging_MessageId_1 } }); - this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext, Constants.UserID_User12); - this._mockMessagingController.Verify(); - } - - [Test] - public void DeleteNotificationRecipient_Does_Not_Delete_Notification_When_There_Are_More_Recipients() - { - var messageRecipients = new List - { - new MessageRecipient(), - }; - - this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)); - this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(messageRecipients); - this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); - - this._mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1), Times.Never()); - } - - [Test] - public void DeleteNotificationRecipient_Deletes_Notification_When_There_Are_No_More_Recipients() - { - this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)); - this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); - this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); - this._mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1)); - } - - [Test] - public void DeleteAllNotificationRecipients_Calls_DeleteNotificationRecipient_For_Each_Recipient() - { - var recipients = new List - { - new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_1 }, - new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_2 }, - }; - - this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(recipients); - - this._mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); - - this._mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Exactly(2)); - } - - [Test] - public void DeleteAllNotificationRecipients_Does_Not_Call_DeleteNotificationRecipient_When_Notification_Has_No_Recipients() - { - this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); - this._mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); - this._mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Never()); - } - - private static Notification CreateUnsavedNotification() - { - return new Notification - { - NotificationTypeID = Constants.Messaging_NotificationTypeId, - Subject = Constants.Messaging_NotificationSubject, - Body = Constants.Messaging_NotificationBody, - To = Constants.UserDisplayName_User12, - From = Constants.UserDisplayName_Admin, - SenderUserID = Constants.UserID_Admin, - Context = Constants.Messaging_NotificationContext, - SendToast = false, - }; - } - - private static Notification CreateValidNotification() - { - var notification = CreateUnsavedNotification(); - notification.NotificationID = Constants.Messaging_MessageId_1; - - return notification; - } - - private static NotificationType CreateValidNotificationType() - { - var nt = CreateNewNotificationType(); - nt.NotificationTypeId = Constants.Messaging_NotificationTypeId; - return nt; - } - - private static NotificationType CreateNewNotificationType() - { - return new NotificationType - { - Name = Constants.Messaging_NotificationTypeName, - Description = Constants.Messaging_NotificationTypeDescription, - TimeToLive = new TimeSpan(0, Constants.Messaging_NotificationTypeTTL, 0), - DesktopModuleId = Constants.Messaging_NotificationTypeDesktopModuleId, - IsTask = false, - }; - } - - private static NotificationTypeAction CreateValidNotificationTypeAction() - { - var action = CreateNewNotificationTypeAction(); - - action.NotificationTypeActionId = Constants.Messaging_NotificationTypeActionId; - action.NotificationTypeId = Constants.Messaging_NotificationTypeId; - - return action; - } - - private static NotificationTypeAction CreateNewNotificationTypeAction() - { - return new NotificationTypeAction - { - APICall = Constants.Messaging_NotificationTypeActionAPICall, - ConfirmResourceKey = Constants.Messaging_NotificationTypeActionConfirmResourceKey, - DescriptionResourceKey = Constants.Messaging_NotificationTypeActionDescriptionResourceKey, - NameResourceKey = Constants.Messaging_NotificationTypeActionNameResourceKey, - }; - } - - private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) - { - var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId }; - return mockPortalInfo; - } - - private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int masterPortalId) - { - var mockPortalGroupInfo = new PortalGroupInfo - { - PortalGroupId = portalGroupId, - MasterPortalId = masterPortalId, - PortalGroupName = Constants.PORTALGROUP_ValidName, - PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, - }; - - return mockPortalGroupInfo; - } - - private void SetupDataProvider() - { - // Standard DataProvider Path for Logging - this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - } - - private void SetupDataTables() - { - this._dtNotificationTypes = new DataTable(); - this._dtNotificationTypes.Columns.Add("NotificationTypeID", typeof(int)); - this._dtNotificationTypes.Columns.Add("Name", typeof(string)); - this._dtNotificationTypes.Columns.Add("Description", typeof(string)); - this._dtNotificationTypes.Columns.Add("TTL", typeof(int)); - this._dtNotificationTypes.Columns.Add("DesktopModuleID", typeof(int)); - this._dtNotificationTypes.Columns.Add("CreatedByUserID", typeof(int)); - this._dtNotificationTypes.Columns.Add("CreatedOnDate", typeof(DateTime)); - this._dtNotificationTypes.Columns.Add("LastModifiedByUserID", typeof(int)); - this._dtNotificationTypes.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - this._dtNotificationTypes.Columns.Add("IsTask", typeof(bool)); - - this._dtNotificationTypeActions = new DataTable(); - this._dtNotificationTypeActions.Columns.Add("NotificationTypeActionID", typeof(int)); - this._dtNotificationTypeActions.Columns.Add("NotificationTypeID", typeof(int)); - this._dtNotificationTypeActions.Columns.Add("NameResourceKey", typeof(string)); - this._dtNotificationTypeActions.Columns.Add("DescriptionResourceKey", typeof(string)); - this._dtNotificationTypeActions.Columns.Add("ConfirmResourceKey", typeof(string)); - this._dtNotificationTypeActions.Columns.Add("Order", typeof(int)); - this._dtNotificationTypeActions.Columns.Add("APICall", typeof(string)); - this._dtNotificationTypeActions.Columns.Add("CreatedByUserID", typeof(int)); - this._dtNotificationTypeActions.Columns.Add("CreatedOnDate", typeof(DateTime)); - this._dtNotificationTypeActions.Columns.Add("LastModifiedByUserID", typeof(int)); - this._dtNotificationTypeActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - this._dtNotificationActions = new DataTable(); - this._dtNotificationActions.Columns.Add("NotificationActionID"); - this._dtNotificationActions.Columns.Add("MessageID"); - this._dtNotificationActions.Columns.Add("NotificationTypeActionID"); - this._dtNotificationActions.Columns.Add("Key"); - this._dtNotificationActions.Columns.Add("CreatedByUserID", typeof(int)); - this._dtNotificationActions.Columns.Add("CreatedOnDate", typeof(DateTime)); - this._dtNotificationActions.Columns.Add("LastModifiedByUserID", typeof(int)); - this._dtNotificationActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - } - - private class NotificationTypeComparer : IEqualityComparer - { - public bool Equals(NotificationType x, NotificationType y) - { - if (x == null) - { - return y == null; - } - - if (y == null) - { - return false; - } - - return - x.NotificationTypeId == y.NotificationTypeId && - x.Name == y.Name && - x.Description == y.Description && - x.TimeToLive == y.TimeToLive && - x.IsTask == y.IsTask && - x.DesktopModuleId == y.DesktopModuleId; - } - - public int GetHashCode(NotificationType obj) - { - throw new NotImplementedException(); - } - } - - private class NotificationTypeActionComparer : IEqualityComparer - { - public bool Equals(NotificationTypeAction x, NotificationTypeAction y) - { - if (x == null) - { - return y == null; - } - - if (y == null) - { - return false; - } - - return - x.NotificationTypeActionId == y.NotificationTypeActionId && - x.NotificationTypeId == y.NotificationTypeId && - x.NameResourceKey == y.NameResourceKey && - x.DescriptionResourceKey == y.DescriptionResourceKey && - x.ConfirmResourceKey == y.ConfirmResourceKey && - x.APICall == y.APICall; - } - - public int GetHashCode(NotificationTypeAction obj) - { - throw new NotImplementedException(); - } - } - - private class NotificationComparer : IEqualityComparer - { - public bool Equals(Notification x, Notification y) - { - if (x == null) - { - return y == null; - } - - if (y == null) - { - return false; - } - - return - x.NotificationID == y.NotificationID && - x.NotificationTypeID == y.NotificationTypeID && - x.Subject == y.Subject && - x.Body == y.Body && - x.To == y.To && - x.From == y.From && - x.SenderUserID == y.SenderUserID && - x.Context == y.Context && - x.IncludeDismissAction == y.IncludeDismissAction; - } - - public int GetHashCode(Notification obj) - { - throw new NotImplementedException(); - } - } - } -} - -// ReSharper restore InconsistentNaming + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + ComponentFactory.Container = new SimpleContainer(); + + this._mockDataService = new Mock(); + this._portalController = new Mock(); + this._portalGroupController = new Mock(); + + this._mockMessagingDataService = new Mock(); + this._dataProvider = MockComponentProvider.CreateDataProvider(); + this._cachingProvider = MockComponentProvider.CreateDataCacheProvider(); + + this._notificationsController = new NotificationsController(this._mockDataService.Object, this._mockMessagingDataService.Object); + this._mockNotificationsController = new Mock { CallBase = true }; + + this._mockMessagingController = new Mock(); + MessagingController.SetTestableInstance(this._mockMessagingController.Object); + PortalController.SetTestableInstance(this._portalController.Object); + PortalGroupController.RegisterInstance(this._portalGroupController.Object); + + this._mockInternalMessagingController = new Mock(); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + + DataService.RegisterInstance(this._mockDataService.Object); + DotNetNuke.Services.Social.Messaging.Data.DataService.RegisterInstance(this._mockMessagingDataService.Object); + + this.SetupDataProvider(); + this.SetupDataTables(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + ComponentFactory.Container = null; + MessagingController.ClearInstance(); + PortalController.ClearInstance(); + InternalMessagingController.ClearInstance(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void CreateNotificationType_Throws_On_Null_NotificationType() + { + this._notificationsController.CreateNotificationType(null); + } + + [Test] + [TestCase("")] + [TestCase(null)] + [ExpectedException(typeof(ArgumentException))] + public void CreateNotificationType_Throws_On_Null_Or_Empty_Name(string name) + { + var notificationType = CreateNewNotificationType(); + notificationType.Name = name; + + this._notificationsController.CreateNotificationType(notificationType); + } + + [Test] + public void CreateNotificationType_Calls_DataService_CreateNotificationType() + { + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + + this._mockDataService + .Setup(ds => ds.CreateNotificationType(Constants.Messaging_NotificationTypeName, It.IsAny(), It.IsAny(), It.IsAny(), Constants.UserID_User12, It.IsAny())) + .Verifiable(); + + this._mockNotificationsController.Object.CreateNotificationType(CreateNewNotificationType()); + + this._mockDataService.Verify(); + } + + [Test] + [TestCase(int.MaxValue, int.MaxValue)] + [TestCase(1, 1)] + [TestCase(0, 0)] + public void CreateNotificationType_Returns_Object_With_Valid_TimeToLive(int actualTimeToLiveTotalMinutes, int expectedTimeToLiveTotalMinutes) + { + var actualTimeToLive = TimeSpan.FromMinutes(actualTimeToLiveTotalMinutes); + + var notificationType = CreateNewNotificationType(); + notificationType.TimeToLive = actualTimeToLive; + this._notificationsController.CreateNotificationType(notificationType); + + Assert.AreEqual(expectedTimeToLiveTotalMinutes, (int)notificationType.TimeToLive.TotalMinutes); + } + + [Test] + public void CreateNotificationType_Makes_Valid_Object() + { + var expectedNotificationType = CreateValidNotificationType(); + + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + + this._mockDataService + .Setup(ds => ds.CreateNotificationType( + expectedNotificationType.Name, + expectedNotificationType.Description, + (int)expectedNotificationType.TimeToLive.TotalMinutes, + expectedNotificationType.DesktopModuleId, + Constants.UserID_User12, false)) + .Returns(Constants.Messaging_NotificationTypeId); + + var actualNotificationType = CreateNewNotificationType(); + this._mockNotificationsController.Object.CreateNotificationType(actualNotificationType); + + Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); + } + + [Test] + public void DeleteNotificationType_Calls_DataService_DeleteNotificationType() + { + this._mockDataService.Setup(ds => ds.DeleteNotificationType(Constants.Messaging_NotificationTypeId)).Verifiable(); + this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()); + this._mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); + this._mockDataService.Verify(); + } + + [Test] + public void DeleteNotificationType_Removes_Cache_Object() + { + this._mockDataService.Setup(ds => ds.DeleteNotificationType(Constants.Messaging_NotificationTypeId)); + this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()).Verifiable(); + this._mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); + this._mockNotificationsController.Verify(); + } + + [Test] + public void GetNotificationType_By_Id_Gets_Object_From_Cache() + { + this._cachingProvider.Object.PurgeCache(); + this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); + this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); + this._cachingProvider.Verify(); + } + + [Test] + public void GetNotificationType_By_Id_Calls_DataService_GetNotificationType_When_Object_Is_Not_In_Cache() + { + this._cachingProvider.Object.PurgeCache(); + + var messageTypeDataTable = new DataTable(); + + this._mockDataService + .Setup(ds => ds.GetNotificationType(Constants.Messaging_NotificationTypeId)) + .Returns(messageTypeDataTable.CreateDataReader()) + .Verifiable(); + + this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); + + this._mockDataService.Verify(); + } + + [Test] + public void GetNotificationType_By_Id_Returns_Valid_Object() + { + this._cachingProvider.Object.PurgeCache(); + + var expectedNotificationType = CreateValidNotificationType(); + + this._dtNotificationTypes.Rows.Clear(); + + this._dtNotificationTypes.Rows.Add( + expectedNotificationType.NotificationTypeId, + expectedNotificationType.Name, + expectedNotificationType.Description, + (int)expectedNotificationType.TimeToLive.TotalMinutes, + expectedNotificationType.DesktopModuleId); + + this._mockDataService + .Setup(ds => ds.GetNotificationType(Constants.Messaging_NotificationTypeId)) + .Returns(this._dtNotificationTypes.CreateDataReader()); + + var actualNotificationType = this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); + + Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void GetNotificationType_By_Name_Throws_On_Null_Or_Empty_Name(string name) + { + this._notificationsController.GetNotificationType(name); + } + + [Test] + public void GetNotificationType_By_Name_Gets_Object_From_Cache() + { + this._cachingProvider.Object.PurgeCache(); + this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); + this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); + this._cachingProvider.Verify(); + } + + [Test] + public void GetNotificationType_By_Name_Calls_DataService_GetNotificationTypeByName_When_Object_Is_Not_In_Cache() + { + this._cachingProvider.Object.PurgeCache(); + + this._mockDataService + .Setup(ds => ds.GetNotificationTypeByName(Constants.Messaging_NotificationTypeName)) + .Returns(this._dtNotificationTypes.CreateDataReader()) + .Verifiable(); + + this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); + + this._mockDataService.Verify(); + } + + [Test] + public void GetNotificationType_By_Name_Returns_Valid_Object() + { + this._cachingProvider.Object.PurgeCache(); + + var expectedNotificationType = CreateValidNotificationType(); + + this._dtNotificationTypes.Rows.Clear(); + + this._dtNotificationTypes.Rows.Add( + expectedNotificationType.NotificationTypeId, + expectedNotificationType.Name, + expectedNotificationType.Description, + (int)expectedNotificationType.TimeToLive.TotalMinutes, + expectedNotificationType.DesktopModuleId); + + this._mockDataService + .Setup(ds => ds.GetNotificationTypeByName(Constants.Messaging_NotificationTypeName)) + .Returns(this._dtNotificationTypes.CreateDataReader()); + + var actualNotificationType = this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); + + Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void SetNotificationTypeActions_Throws_On_Null() + { + this._notificationsController.SetNotificationTypeActions(null, Constants.Messaging_NotificationTypeId); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SetNotificationTypeActions_Throws_On_EmptyList() + { + this._notificationsController.SetNotificationTypeActions(new List(), Constants.Messaging_NotificationTypeId); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void SetNotificationTypeActions_Throws_On_Null_Or_Empty_Name(string name) + { + var action = CreateNewNotificationTypeAction(); + action.NameResourceKey = name; + this._notificationsController.SetNotificationTypeActions(new[] { action }, Constants.Messaging_NotificationTypeId); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void SetNotificationTypeActions_Throws_On_Null_Or_Empty_APICall(string apiCall) + { + var action = CreateNewNotificationTypeAction(); + action.APICall = apiCall; + this._notificationsController.SetNotificationTypeActions(new[] { action }, Constants.Messaging_NotificationTypeId); + } + + [Test] + public void SetNotificationTypeActions_Calls_DataService_AddNotificationTypeAction_For_Each_Of_Two_Actions() + { + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + + // _mockDataService + // .Setup(ds => ds.AddNotificationTypeAction( + // Constants.Messaging_NotificationTypeId, + // Constants.Messaging_NotificationTypeActionNameResourceKey, + // Constants.Messaging_NotificationTypeActionDescriptionResourceKey, + // Constants.Messaging_NotificationTypeActionConfirmResourceKey, + // Constants.Messaging_NotificationTypeActionAPICall, + // Constants.UserID_User12)) + // .Verifiable(); + this._mockNotificationsController.Setup(nc => nc.GetNotificationTypeAction(It.IsAny())); + + this._mockNotificationsController.Object.SetNotificationTypeActions( + new[] { CreateNewNotificationTypeAction(), CreateNewNotificationTypeAction() }, + Constants.Messaging_NotificationTypeId); + + this._mockDataService.Verify( + x => x.AddNotificationTypeAction( + Constants.Messaging_NotificationTypeId, + Constants.Messaging_NotificationTypeActionNameResourceKey, + Constants.Messaging_NotificationTypeActionDescriptionResourceKey, + Constants.Messaging_NotificationTypeActionConfirmResourceKey, + Constants.Messaging_NotificationTypeActionAPICall, + Constants.UserID_User12), Times.Exactly(2)); + } + + [Test] + public void SetNotificationTypeActions_Sets_NotificationTypeActionId_And_NotificationTypeId() + { + var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); + + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + + this._mockDataService + .Setup(ds => ds.AddNotificationTypeAction( + expectedNotificationTypeAction.NotificationTypeId, + expectedNotificationTypeAction.NameResourceKey, + expectedNotificationTypeAction.DescriptionResourceKey, + expectedNotificationTypeAction.ConfirmResourceKey, + expectedNotificationTypeAction.APICall, + Constants.UserID_User12)) + .Returns(expectedNotificationTypeAction.NotificationTypeActionId); + + this._mockNotificationsController + .Setup(nc => nc.GetNotificationTypeAction(expectedNotificationTypeAction.NotificationTypeActionId)) + .Returns(expectedNotificationTypeAction); + + var action = CreateNewNotificationTypeAction(); + this._mockNotificationsController.Object.SetNotificationTypeActions(new[] { action }, expectedNotificationTypeAction.NotificationTypeId); + + Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, action)); + } + + [Test] + public void DeleteNotificationTypeAction_Calls_DataService_DeleteNotificationTypeAction() + { + this._mockDataService.Setup(ds => ds.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)).Verifiable(); + this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()); + this._mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + this._mockDataService.Verify(); + } + + [Test] + public void DeleteNotificationTypeAction_Removes_Cache_Object() + { + this._mockDataService.Setup(ds => ds.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)); + this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()).Verifiable(); + this._mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + this._mockNotificationsController.Verify(); + } + + [Test] + public void GetNotificationTypeAction_By_Id_Gets_Object_From_Cache() + { + this._cachingProvider.Object.PurgeCache(); + this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + this._cachingProvider.Verify(); + } + + [Test] + public void GetNotificationTypeAction_By_Id_Calls_DataService_GetNotificationTypeAction_When_Object_Is_Not_In_Cache() + { + this._cachingProvider.Object.PurgeCache(); + + this._mockDataService + .Setup(ds => ds.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)) + .Returns(this._dtNotificationTypeActions.CreateDataReader()) + .Verifiable(); + + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + + this._mockDataService.Verify(); + } + + [Test] + public void GetNotificationTypeAction_By_Id_Returns_Valid_Object() + { + this._cachingProvider.Object.PurgeCache(); + + var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); + + this._dtNotificationTypeActions.Clear(); + + this._dtNotificationTypeActions.Rows.Add( + expectedNotificationTypeAction.NotificationTypeActionId, + expectedNotificationTypeAction.NotificationTypeId, + expectedNotificationTypeAction.NameResourceKey, + expectedNotificationTypeAction.DescriptionResourceKey, + expectedNotificationTypeAction.ConfirmResourceKey, + expectedNotificationTypeAction.Order, + expectedNotificationTypeAction.APICall); + + this._mockDataService + .Setup(ds => ds.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)) + .Returns(this._dtNotificationTypeActions.CreateDataReader); + + var actualNotificationTypeAction = this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + + Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeAction)); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void GetNotificationTypeAction_By_Name_Throws_On_Null_Or_Empty_Name(string name) + { + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, name); + } + + [Test] + public void GetNotificationTypeAction_By_Name_Gets_Object_From_Cache() + { + this._cachingProvider.Object.PurgeCache(); + this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); + this._cachingProvider.Verify(); + } + + [Test] + public void GetNotificationTypeAction_By_Name_Calls_DataService_GetNotificationTypeActionByName_When_Object_Is_Not_In_Cache() + { + this._cachingProvider.Object.PurgeCache(); + + this._mockDataService + .Setup(ds => ds.GetNotificationTypeActionByName( + Constants.Messaging_NotificationTypeId, + Constants.Messaging_NotificationTypeActionNameResourceKey)) + .Returns(this._dtNotificationTypeActions.CreateDataReader()) + .Verifiable(); + + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); + + this._mockDataService.Verify(); + } + + [Test] + public void GetNotificationTypeAction_By_Name_Returns_Valid_Object() + { + this._cachingProvider.Object.PurgeCache(); + + var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); + + this._dtNotificationTypeActions.Clear(); + + this._dtNotificationTypeActions.Rows.Add( + expectedNotificationTypeAction.NotificationTypeActionId, + expectedNotificationTypeAction.NotificationTypeId, + expectedNotificationTypeAction.NameResourceKey, + expectedNotificationTypeAction.DescriptionResourceKey, + expectedNotificationTypeAction.ConfirmResourceKey, + expectedNotificationTypeAction.Order, + expectedNotificationTypeAction.APICall); + + this._mockDataService + .Setup(ds => ds.GetNotificationTypeActionByName( + Constants.Messaging_NotificationTypeId, + Constants.Messaging_NotificationTypeActionNameResourceKey)) + .Returns(this._dtNotificationTypeActions.CreateDataReader()); + + var actualNotificationTypeAction = this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); + + Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeAction)); + } + + [Test] + public void GetNotificationTypeActions_Calls_DataService_GetNotificationTypeActions() + { + this._mockDataService + .Setup(ds => ds.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId)) + .Returns(this._dtNotificationTypeActions.CreateDataReader()) + .Verifiable(); + + this._notificationsController.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId); + + this._mockDataService.Verify(); + } + + [Test] + public void GetNotificationTypeActions_Returns_Valid_Object() + { + var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); + + this._dtNotificationTypeActions.Clear(); + + this._dtNotificationTypeActions.Rows.Add( + expectedNotificationTypeAction.NotificationTypeActionId, + expectedNotificationTypeAction.NotificationTypeId, + expectedNotificationTypeAction.NameResourceKey, + expectedNotificationTypeAction.DescriptionResourceKey, + expectedNotificationTypeAction.ConfirmResourceKey, + expectedNotificationTypeAction.Order, + expectedNotificationTypeAction.APICall); + + this._mockDataService.Setup(ds => ds.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId)).Returns(this._dtNotificationTypeActions.CreateDataReader()); + + var actualNotificationTypeActions = this._notificationsController.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId); + + Assert.AreEqual(1, actualNotificationTypeActions.Count); + Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeActions[0])); + } + + [Test] + public void SendNotification_Sets_Empty_SenderUserId_With_Admin() + { + var adminUser = new UserInfo + { + UserID = Constants.UserID_Admin, + DisplayName = Constants.UserDisplayName_Admin, + PortalID = Constants.CONTENT_ValidPortalId, + }; + + this._mockNotificationsController.Setup(nc => nc.GetAdminUser()).Returns(adminUser); + + this._mockNotificationsController + .Setup(nc => nc.SendNotification( + It.IsAny(), + Constants.PORTAL_Zero, + It.IsAny>(), + It.IsAny>())); + + var notification = CreateUnsavedNotification(); + + this._mockNotificationsController.Object.SendNotification( + notification, + Constants.PORTAL_Zero, + new List(), + new List()); + + Assert.AreEqual(adminUser.UserID, notification.SenderUserID); + } + + [Test] + [TestCase(null, null)] + [TestCase(null, "")] + [TestCase("", null)] + [TestCase("", "")] + [ExpectedException(typeof(ArgumentException))] + public void SendNotification_Throws_On_Null_Or_Empty_Subject_And_Body(string subject, string body) + { + var notification = CreateUnsavedNotification(); + notification.Subject = subject; + notification.Body = body; + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + this._notificationsController.SendNotification( + notification, + Constants.PORTAL_Zero, + new List(), + new List()); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SendNotification_Throws_On_Null_Roles_And_Users() + { + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + this._notificationsController.SendNotification( + CreateUnsavedNotification(), + Constants.PORTAL_Zero, + null, + null); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SendNotification_Throws_On_Large_Subject() + { + var notification = CreateUnsavedNotification(); + var subject = new StringBuilder(); + for (var i = 0; i <= 40; i++) + { + subject.Append("1234567890"); + } + + notification.Subject = subject.ToString(); + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + this._notificationsController.SendNotification( + notification, + Constants.PORTAL_Zero, + new List(), + new List()); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SendNotification_Throws_On_Roles_And_Users_With_No_DisplayNames() + { + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + this._notificationsController.SendNotification( + CreateUnsavedNotification(), + Constants.PORTAL_Zero, + new List(), + new List()); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SendNotification_Throws_On_Large_To_List() + { + var roles = new List(); + var users = new List(); + + for (var i = 0; i <= 100; i++) + { + roles.Add(new RoleInfo { RoleName = "1234567890" }); + users.Add(new UserInfo { DisplayName = "1234567890" }); + } + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + this._notificationsController.SendNotification( + CreateUnsavedNotification(), + Constants.PORTAL_Zero, + roles, + users); + } + + [Test] + public void SendNotification_Calls_DataService_On_Valid_Notification() + { + var adminUser = new UserInfo + { + UserID = Constants.UserID_Admin, + DisplayName = Constants.UserDisplayName_Admin, + PortalID = Constants.PORTAL_Zero, + }; + + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + var roles = new List(); + var users = new List + { + new UserInfo + { + UserID = Constants.UserID_User12, + DisplayName = Constants.UserDisplayName_User12 + }, + }; + + this._mockDataService + .Setup(ds => ds.SendNotification( + It.IsAny(), + Constants.PORTAL_Zero)) + .Verifiable(); + + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + + var notification = CreateUnsavedNotification(); + notification.SenderUserID = adminUser.UserID; + notification.SendToast = false; + + this._mockNotificationsController.Object.SendNotification( + notification, + Constants.PORTAL_Zero, + roles, + users); + + this._mockDataService.Verify(); + } + + [Test] + public void SendNotification_Calls_DataService_On_Valid_Notification_When_Portal_Is_In_Group() + { + var adminUser = new UserInfo + { + UserID = Constants.UserID_Admin, + DisplayName = Constants.UserDisplayName_Admin, + PortalID = Constants.PORTAL_Zero, + }; + + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); + this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); + + var roles = new List(); + var users = new List + { + new UserInfo + { + UserID = Constants.UserID_User12, + DisplayName = Constants.UserDisplayName_User12 + }, + }; + + this._mockDataService + .Setup(ds => ds.SendNotification( + It.IsAny(), + Constants.PORTAL_Zero)) + .Verifiable(); + + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + + var notification = CreateUnsavedNotification(); + notification.SenderUserID = adminUser.UserID; + notification.SendToast = false; + + this._mockNotificationsController.Object.SendNotification( + notification, + Constants.PORTAL_Zero, + roles, + users); + + this._mockDataService.Verify(); + } + + [Test] + public void SendNotification_Calls_Messaging_DataService_CreateSocialMessageRecipientsForRole_When_Passing_Roles() + { + var adminUser = new UserInfo + { + UserID = Constants.UserID_Admin, + DisplayName = Constants.UserDisplayName_Admin, + PortalID = Constants.PORTAL_Zero, + }; + + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + var roles = new List + { + new RoleInfo + { + RoleID = Constants.RoleID_RegisteredUsers, + RoleName = Constants.RoleName_RegisteredUsers + }, + }; + var users = new List(); + + this._mockDataService + .Setup(ds => ds.SendNotification( + It.IsAny(), + Constants.PORTAL_Zero)) + .Returns(Constants.Messaging_MessageId_1); + + this._mockMessagingDataService + .Setup(mds => mds.CreateMessageRecipientsForRole( + Constants.Messaging_MessageId_1, + Constants.RoleID_RegisteredUsers.ToString(CultureInfo.InvariantCulture), + It.IsAny())) + .Verifiable(); + + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + + var notification = CreateUnsavedNotification(); + notification.SenderUserID = adminUser.UserID; + notification.SendToast = false; + + this._mockNotificationsController.Object.SendNotification( + notification, + Constants.PORTAL_Zero, + roles, + users); + + this._mockMessagingDataService.Verify(); + } + + [Test] + public void SendNotification_Calls_Messaging_DataService_SaveSocialMessageRecipient_When_Passing_Users() + { + var adminUser = new UserInfo + { + UserID = Constants.UserID_Admin, + DisplayName = Constants.UserDisplayName_Admin, + PortalID = Constants.PORTAL_Zero, + }; + + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + var roles = new List(); + var users = new List + { + new UserInfo + { + UserID = Constants.UserID_User12, + DisplayName = Constants.UserDisplayName_User12 + }, + }; + + this._mockDataService + .Setup(ds => ds.SendNotification( + It.IsAny(), + Constants.PORTAL_Zero)) + .Returns(Constants.Messaging_MessageId_1); + + this._mockInternalMessagingController + .Setup(mc => mc.GetMessageRecipient( + Constants.Messaging_MessageId_1, + Constants.UserID_User12)) + .Returns((MessageRecipient)null); + + this._mockMessagingDataService + .Setup(mds => mds.SaveMessageRecipient( + It.Is(mr => + mr.MessageID == Constants.Messaging_MessageId_1 && + mr.UserID == Constants.UserID_User12 && + mr.Read == false && + mr.RecipientID == Null.NullInteger), + It.IsAny())) + .Verifiable(); + + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + + var notification = CreateUnsavedNotification(); + notification.SenderUserID = adminUser.UserID; + notification.SendToast = false; + + this._mockNotificationsController.Object.SendNotification( + notification, + Constants.PORTAL_Zero, + roles, + users); + + this._mockMessagingDataService.Verify(); + } + + [Test] + public void SendNotification_Returns_Valid_Object() + { + var expectedNotification = CreateValidNotification(); + + var adminUser = new UserInfo + { + UserID = Constants.UserID_Admin, + DisplayName = Constants.UserDisplayName_Admin, + PortalID = Constants.PORTAL_Zero, + }; + + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + var roles = new List(); + var users = new List + { + new UserInfo + { + UserID = Constants.UserID_User12, + DisplayName = Constants.UserDisplayName_User12 + }, + }; + + this._mockDataService + .Setup(ds => ds.SendNotification( + It.IsAny(), + Constants.PORTAL_Zero)) + .Returns(Constants.Messaging_MessageId_1); + + this._mockMessagingDataService + .Setup(mds => mds.CreateMessageRecipientsForRole( + Constants.Messaging_MessageId_1, + Constants.RoleID_RegisteredUsers.ToString(CultureInfo.InvariantCulture), + It.IsAny())); + + this._mockInternalMessagingController + .Setup(mc => mc.GetMessageRecipient( + Constants.Messaging_MessageId_1, + Constants.UserID_User12)) + .Returns((MessageRecipient)null); + + this._mockMessagingDataService + .Setup(mds => mds.SaveMessageRecipient( + It.Is(mr => + mr.MessageID == Constants.Messaging_MessageId_1 && + mr.UserID == Constants.UserID_User12 && + mr.Read == false && + mr.RecipientID == Null.NullInteger), + It.IsAny())); + + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + + var notification = CreateUnsavedNotification(); + notification.SenderUserID = adminUser.UserID; + notification.SendToast = false; + + this._mockNotificationsController.Object.SendNotification( + notification, + Constants.PORTAL_Zero, + roles, + users); + + Assert.IsTrue(new NotificationComparer().Equals(expectedNotification, notification)); + } + + [Test] + public void DeleteNotification_Calls_DataService_DeleteNotification() + { + var messageRecipients = new List + { + new MessageRecipient(), + }; + + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(messageRecipients); + + this._mockDataService.Setup(ds => ds.DeleteNotification(Constants.Messaging_MessageId_1)).Verifiable(); + this._notificationsController.DeleteNotification(Constants.Messaging_MessageId_1); + this._mockDataService.Verify(); + } + + [Test] + public void GetNotifications_Calls_DataService_GetNotifications() + { + this._mockDataService + .Setup(ds => ds.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, It.IsAny(), It.IsAny())) + .Returns(new DataTable().CreateDataReader()) + .Verifiable(); + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + this._notificationsController.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, 0, 10); + this._mockDataService.Verify(); + } + + [Test] + public void GetNotifications_Calls_DataService_GetNotifications_When_Portal_Is_In_Group() + { + this._mockDataService + .Setup(ds => ds.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, It.IsAny(), It.IsAny())) + .Returns(new DataTable().CreateDataReader()) + .Verifiable(); + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); + this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); + + this._notificationsController.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, 0, 10); + this._mockDataService.Verify(); + } + + [Test] + public void GetNotifications_Calls_DataService_GetNotificationByContext() + { + this._mockDataService + .Setup(ds => ds.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext)) + .Returns(new DataTable().CreateDataReader()) + .Verifiable(); + + this._notificationsController.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext); + this._mockDataService.Verify(); + } + + [Test] + public void CountNotifications_Calls_DataService_CountNotifications() + { + this._mockDataService.Setup(ds => ds.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero)).Verifiable(); + this._notificationsController.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero); + this._mockDataService.Verify(); + } + + [Test] + public void DeleteNotificationRecipient_Calls_MessagingController_DeleteMessageRecipient() + { + this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); + this._notificationsController.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); + this._mockMessagingController.Verify(); + } + + [Test] + public void DeleteNotificationRecipientByContext_Calls_DeleteMessageRecipient() + { + this._mockNotificationsController.Setup(mc => mc.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); + this._mockNotificationsController.Setup(mc => mc.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext)) + .Returns(new List { new Notification { NotificationID = Constants.Messaging_MessageId_1 } }); + this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext, Constants.UserID_User12); + this._mockMessagingController.Verify(); + } + + [Test] + public void DeleteNotificationRecipient_Does_Not_Delete_Notification_When_There_Are_More_Recipients() + { + var messageRecipients = new List + { + new MessageRecipient(), + }; + + this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)); + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(messageRecipients); + this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); + + this._mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1), Times.Never()); + } + + [Test] + public void DeleteNotificationRecipient_Deletes_Notification_When_There_Are_No_More_Recipients() + { + this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)); + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); + this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); + this._mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1)); + } + + [Test] + public void DeleteAllNotificationRecipients_Calls_DeleteNotificationRecipient_For_Each_Recipient() + { + var recipients = new List + { + new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_1 }, + new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_2 }, + }; + + this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(recipients); + + this._mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); + + this._mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Exactly(2)); + } + + [Test] + public void DeleteAllNotificationRecipients_Does_Not_Call_DeleteNotificationRecipient_When_Notification_Has_No_Recipients() + { + this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); + this._mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); + this._mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Never()); + } + + private static Notification CreateUnsavedNotification() + { + return new Notification + { + NotificationTypeID = Constants.Messaging_NotificationTypeId, + Subject = Constants.Messaging_NotificationSubject, + Body = Constants.Messaging_NotificationBody, + To = Constants.UserDisplayName_User12, + From = Constants.UserDisplayName_Admin, + SenderUserID = Constants.UserID_Admin, + Context = Constants.Messaging_NotificationContext, + SendToast = false, + }; + } + + private static Notification CreateValidNotification() + { + var notification = CreateUnsavedNotification(); + notification.NotificationID = Constants.Messaging_MessageId_1; + + return notification; + } + + private static NotificationType CreateValidNotificationType() + { + var nt = CreateNewNotificationType(); + nt.NotificationTypeId = Constants.Messaging_NotificationTypeId; + return nt; + } + + private static NotificationType CreateNewNotificationType() + { + return new NotificationType + { + Name = Constants.Messaging_NotificationTypeName, + Description = Constants.Messaging_NotificationTypeDescription, + TimeToLive = new TimeSpan(0, Constants.Messaging_NotificationTypeTTL, 0), + DesktopModuleId = Constants.Messaging_NotificationTypeDesktopModuleId, + IsTask = false, + }; + } + + private static NotificationTypeAction CreateValidNotificationTypeAction() + { + var action = CreateNewNotificationTypeAction(); + + action.NotificationTypeActionId = Constants.Messaging_NotificationTypeActionId; + action.NotificationTypeId = Constants.Messaging_NotificationTypeId; + + return action; + } + + private static NotificationTypeAction CreateNewNotificationTypeAction() + { + return new NotificationTypeAction + { + APICall = Constants.Messaging_NotificationTypeActionAPICall, + ConfirmResourceKey = Constants.Messaging_NotificationTypeActionConfirmResourceKey, + DescriptionResourceKey = Constants.Messaging_NotificationTypeActionDescriptionResourceKey, + NameResourceKey = Constants.Messaging_NotificationTypeActionNameResourceKey, + }; + } + + private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) + { + var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId }; + return mockPortalInfo; + } + + private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int masterPortalId) + { + var mockPortalGroupInfo = new PortalGroupInfo + { + PortalGroupId = portalGroupId, + MasterPortalId = masterPortalId, + PortalGroupName = Constants.PORTALGROUP_ValidName, + PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, + }; + + return mockPortalGroupInfo; + } + + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + } + + private void SetupDataTables() + { + this._dtNotificationTypes = new DataTable(); + this._dtNotificationTypes.Columns.Add("NotificationTypeID", typeof(int)); + this._dtNotificationTypes.Columns.Add("Name", typeof(string)); + this._dtNotificationTypes.Columns.Add("Description", typeof(string)); + this._dtNotificationTypes.Columns.Add("TTL", typeof(int)); + this._dtNotificationTypes.Columns.Add("DesktopModuleID", typeof(int)); + this._dtNotificationTypes.Columns.Add("CreatedByUserID", typeof(int)); + this._dtNotificationTypes.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtNotificationTypes.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtNotificationTypes.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + this._dtNotificationTypes.Columns.Add("IsTask", typeof(bool)); + + this._dtNotificationTypeActions = new DataTable(); + this._dtNotificationTypeActions.Columns.Add("NotificationTypeActionID", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("NotificationTypeID", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("NameResourceKey", typeof(string)); + this._dtNotificationTypeActions.Columns.Add("DescriptionResourceKey", typeof(string)); + this._dtNotificationTypeActions.Columns.Add("ConfirmResourceKey", typeof(string)); + this._dtNotificationTypeActions.Columns.Add("Order", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("APICall", typeof(string)); + this._dtNotificationTypeActions.Columns.Add("CreatedByUserID", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtNotificationTypeActions.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + + this._dtNotificationActions = new DataTable(); + this._dtNotificationActions.Columns.Add("NotificationActionID"); + this._dtNotificationActions.Columns.Add("MessageID"); + this._dtNotificationActions.Columns.Add("NotificationTypeActionID"); + this._dtNotificationActions.Columns.Add("Key"); + this._dtNotificationActions.Columns.Add("CreatedByUserID", typeof(int)); + this._dtNotificationActions.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtNotificationActions.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtNotificationActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + } + + private class NotificationTypeComparer : IEqualityComparer + { + public bool Equals(NotificationType x, NotificationType y) + { + if (x == null) + { + return y == null; + } + + if (y == null) + { + return false; + } + + return + x.NotificationTypeId == y.NotificationTypeId && + x.Name == y.Name && + x.Description == y.Description && + x.TimeToLive == y.TimeToLive && + x.IsTask == y.IsTask && + x.DesktopModuleId == y.DesktopModuleId; + } + + public int GetHashCode(NotificationType obj) + { + throw new NotImplementedException(); + } + } + + private class NotificationTypeActionComparer : IEqualityComparer + { + public bool Equals(NotificationTypeAction x, NotificationTypeAction y) + { + if (x == null) + { + return y == null; + } + + if (y == null) + { + return false; + } + + return + x.NotificationTypeActionId == y.NotificationTypeActionId && + x.NotificationTypeId == y.NotificationTypeId && + x.NameResourceKey == y.NameResourceKey && + x.DescriptionResourceKey == y.DescriptionResourceKey && + x.ConfirmResourceKey == y.ConfirmResourceKey && + x.APICall == y.APICall; + } + + public int GetHashCode(NotificationTypeAction obj) + { + throw new NotImplementedException(); + } + } + + private class NotificationComparer : IEqualityComparer + { + public bool Equals(Notification x, Notification y) + { + if (x == null) + { + return y == null; + } + + if (y == null) + { + return false; + } + + return + x.NotificationID == y.NotificationID && + x.NotificationTypeID == y.NotificationTypeID && + x.Subject == y.Subject && + x.Body == y.Body && + x.To == y.To && + x.From == y.From && + x.SenderUserID == y.SenderUserID && + x.Context == y.Context && + x.IncludeDismissAction == y.IncludeDismissAction; + } + + public int GetHashCode(Notification obj) + { + throw new NotImplementedException(); + } + } + } +} + +// ReSharper restore InconsistentNaming diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs index 81022007ee8..380de00282e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs @@ -2,180 +2,195 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Controllers.Messaging -{ - using System; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.Social.Subscriptions; - using DotNetNuke.Services.Social.Subscriptions.Data; - using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; - using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; - using DotNetNuke.Tests.Utilities.Mocks; - using Moq; - using NUnit.Framework; - - [TestFixture] - public class SubscriptionTypeControllerTests - { - private const string SubscriptionTypesCacheKey = "DNN_" + DataCache.SubscriptionTypesCacheKey; - - private SubscriptionTypeController subscriptionTypeController; - private Mock mockDataService; - private Mock mockCacheProvider; - - [SetUp] - public void SetUp() - { - // Setup Mocks and Stub - this.mockDataService = new Mock(); - this.mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); - - DataService.SetTestableInstance(this.mockDataService.Object); - - // Setup SUT - this.subscriptionTypeController = new SubscriptionTypeController(); - } - - [Test] - public void GetSubscriptionTypes_ShouldCallDataService_WhenNoError() - { - // Arrange - var mockHostController = new Mock(); - mockHostController - .Setup(c => c.GetString("PerformanceSetting")) - .Returns("0"); - HostController.RegisterInstance(mockHostController.Object); - - this.mockDataService - .Setup(ds => ds.GetSubscriptionTypes()) - .Returns(SubscriptionTypeDataReaderMockHelper.CreateEmptySubscriptionTypeReader()) - .Verifiable(); - - // Act - this.subscriptionTypeController.GetSubscriptionTypes(); - - // Assert - this.mockDataService.Verify(ds => ds.GetSubscriptionTypes(), Times.Once()); - } - - [Test] - public void GetSubscriptionTypes_ShouldThrowArgumentNullException_WhenPredicateIsNull() - { - // Act, Arrange - Assert.Throws(() => this.subscriptionTypeController.GetSubscriptionTypes(null)); - } - - [Test] - public void GetSubscriptionType_ShouldThrowArgumentNullException_WhenPredicateIsNull() - { - // Act, Assert - Assert.Throws(() => this.subscriptionTypeController.GetSubscriptionType(null)); - } - - [Test] - public void AddSubscriptionType_ShouldThrowArgumentNullException_WhenSubscriptionTypeIsNull() - { - // Act, Arrange - Assert.Throws(() => this.subscriptionTypeController.AddSubscriptionType(null)); - } - - [Test] - public void AddSubscriptionType_ShouldFilledUpTheSubscriptionTypeIdPropertyOfTheInputSubscriptionTypeEntity_WhenNoError() - { - // Arrange - const int expectedSubscriptionTypeId = 12; - var subscriptionType = new SubscriptionTypeBuilder().Build(); - - this.mockDataService - .Setup(ds => ds.AddSubscriptionType( - subscriptionType.SubscriptionName, - subscriptionType.FriendlyName, - subscriptionType.DesktopModuleId)) - .Returns(expectedSubscriptionTypeId); - - // Act - this.subscriptionTypeController.AddSubscriptionType(subscriptionType); - - // Assert - Assert.AreEqual(expectedSubscriptionTypeId, subscriptionType.SubscriptionTypeId); - } - - [Test] - public void AddSubscriptionType_ShouldCleanCache_WhenNoError() - { - // Arrange - this.mockDataService.Setup(ds => ds.AddSubscriptionType(It.IsAny(), It.IsAny(), It.IsAny())); - this.mockCacheProvider.Setup(cp => cp.Remove(SubscriptionTypesCacheKey)).Verifiable(); - - var subscriptionType = new SubscriptionTypeBuilder().Build(); - - // Act - this.subscriptionTypeController.AddSubscriptionType(subscriptionType); - - // Assert - this.mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); - } - - [Test] - public void DeleteSubscriptionType_ShouldThrowArgumentOutOfRangeException_WhenSubscriptionTypeIdIsNegative() - { - // Arrange - var subscriptionType = new SubscriptionTypeBuilder() - .WithSubscriptionTypeId(-1) - .Build(); - - // Act, Assert - Assert.Throws(() => this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType)); - } - - [Test] - public void DeleteSubscriptionType_ShouldThrowNullArgumentException_WhenSubscriptionTypeIsNull() - { - // Act, Assert - Assert.Throws(() => this.subscriptionTypeController.DeleteSubscriptionType(null)); - } - - [Test] - public void DeleteSubscriptionType_ShouldCallDataService_WhenNoError() - { - // Arrange - var subscriptionType = new SubscriptionTypeBuilder().Build(); - - this.mockDataService - .Setup(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId)) - .Verifiable(); - - // Act - this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType); - - // Assert - this.mockDataService.Verify(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId), Times.Once()); - } - - [Test] - public void DeleteSubscriptionType_ShouldCleanCache_WhenNoError() - { - // Arrange - var subscriptionType = new SubscriptionTypeBuilder().Build(); - - this.mockDataService.Setup(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId)); - this.mockCacheProvider.Setup(cp => cp.Remove(SubscriptionTypesCacheKey)).Verifiable(); - - // Act - this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType); - - // Assert - this.mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); - } - - [TearDown] - public void TearDown() - { - DataService.ClearInstance(); - MockComponentProvider.ResetContainer(); - } - } -} +namespace DotNetNuke.Tests.Core.Controllers.Messaging +{ + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Social.Subscriptions; + using DotNetNuke.Services.Social.Subscriptions.Data; + using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; + using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; + using DotNetNuke.Tests.Utilities.Mocks; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class SubscriptionTypeControllerTests + { + private const string SubscriptionTypesCacheKey = "DNN_" + DataCache.SubscriptionTypesCacheKey; + + private SubscriptionTypeController subscriptionTypeController; + private Mock mockDataService; + private Mock mockCacheProvider; + private Mock mockHostController; + + [SetUp] + public void SetUp() + { + // Setup Mocks and Stub + this.mockDataService = new Mock(); + this.mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); + this.mockHostController = new Mock(); + this.mockHostController.As(); + + DataService.SetTestableInstance(this.mockDataService.Object); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); + serviceCollection.AddTransient(container => (IHostSettingsService)this.mockHostController.Object); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + // Setup SUT + this.subscriptionTypeController = new SubscriptionTypeController(); + } + + [Test] + public void GetSubscriptionTypes_ShouldCallDataService_WhenNoError() + { + // Arrange + this.mockHostController + .Setup(c => c.GetString("PerformanceSetting")) + .Returns("0"); + + this.mockDataService + .Setup(ds => ds.GetSubscriptionTypes()) + .Returns(SubscriptionTypeDataReaderMockHelper.CreateEmptySubscriptionTypeReader()) + .Verifiable(); + + // Act + this.subscriptionTypeController.GetSubscriptionTypes(); + + // Assert + this.mockDataService.Verify(ds => ds.GetSubscriptionTypes(), Times.Once()); + } + + [Test] + public void GetSubscriptionTypes_ShouldThrowArgumentNullException_WhenPredicateIsNull() + { + // Act, Arrange + Assert.Throws(() => this.subscriptionTypeController.GetSubscriptionTypes(null)); + } + + [Test] + public void GetSubscriptionType_ShouldThrowArgumentNullException_WhenPredicateIsNull() + { + // Act, Assert + Assert.Throws(() => this.subscriptionTypeController.GetSubscriptionType(null)); + } + + [Test] + public void AddSubscriptionType_ShouldThrowArgumentNullException_WhenSubscriptionTypeIsNull() + { + // Act, Arrange + Assert.Throws(() => this.subscriptionTypeController.AddSubscriptionType(null)); + } + + [Test] + public void AddSubscriptionType_ShouldFilledUpTheSubscriptionTypeIdPropertyOfTheInputSubscriptionTypeEntity_WhenNoError() + { + // Arrange + const int expectedSubscriptionTypeId = 12; + var subscriptionType = new SubscriptionTypeBuilder().Build(); + + this.mockDataService + .Setup(ds => ds.AddSubscriptionType( + subscriptionType.SubscriptionName, + subscriptionType.FriendlyName, + subscriptionType.DesktopModuleId)) + .Returns(expectedSubscriptionTypeId); + + // Act + this.subscriptionTypeController.AddSubscriptionType(subscriptionType); + + // Assert + Assert.AreEqual(expectedSubscriptionTypeId, subscriptionType.SubscriptionTypeId); + } + + [Test] + public void AddSubscriptionType_ShouldCleanCache_WhenNoError() + { + // Arrange + this.mockDataService.Setup(ds => ds.AddSubscriptionType(It.IsAny(), It.IsAny(), It.IsAny())); + this.mockCacheProvider.Setup(cp => cp.Remove(SubscriptionTypesCacheKey)).Verifiable(); + + var subscriptionType = new SubscriptionTypeBuilder().Build(); + + // Act + this.subscriptionTypeController.AddSubscriptionType(subscriptionType); + + // Assert + this.mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); + } + + [Test] + public void DeleteSubscriptionType_ShouldThrowArgumentOutOfRangeException_WhenSubscriptionTypeIdIsNegative() + { + // Arrange + var subscriptionType = new SubscriptionTypeBuilder() + .WithSubscriptionTypeId(-1) + .Build(); + + // Act, Assert + Assert.Throws(() => this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType)); + } + + [Test] + public void DeleteSubscriptionType_ShouldThrowNullArgumentException_WhenSubscriptionTypeIsNull() + { + // Act, Assert + Assert.Throws(() => this.subscriptionTypeController.DeleteSubscriptionType(null)); + } + + [Test] + public void DeleteSubscriptionType_ShouldCallDataService_WhenNoError() + { + // Arrange + var subscriptionType = new SubscriptionTypeBuilder().Build(); + + this.mockDataService + .Setup(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId)) + .Verifiable(); + + // Act + this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType); + + // Assert + this.mockDataService.Verify(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId), Times.Once()); + } + + [Test] + public void DeleteSubscriptionType_ShouldCleanCache_WhenNoError() + { + // Arrange + var subscriptionType = new SubscriptionTypeBuilder().Build(); + + this.mockDataService.Setup(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId)); + this.mockCacheProvider.Setup(cp => cp.Remove(SubscriptionTypesCacheKey)).Verifiable(); + + // Act + this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType); + + // Assert + this.mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + DataService.ClearInstance(); + MockComponentProvider.ResetContainer(); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs index 824af839ab3..f4c79d823ca 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs @@ -2,520 +2,535 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Controllers.Portal -{ - using System; - using System.Collections.Generic; - using System.Data; - using System.Linq; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Portals.Data; - using DotNetNuke.Services.Cache; - using DotNetNuke.Tests.Utilities; - using DotNetNuke.Tests.Utilities.Mocks; - using Moq; - using NUnit.Framework; - - // ReSharper disable InconsistentNaming - [TestFixture] - public class PortalGroupControllerTests - { - private Mock _mockData; -#pragma warning disable 649 - private UserCopiedCallback userCopied; -#pragma warning restore 649 - - [SetUp] - public void SetUp() - { - this._mockData = MockComponentProvider.CreateDataProvider(); - DataTable hostSettingsTable = new DataTable("HostSettings"); - - var nameCol = hostSettingsTable.Columns.Add("SettingName"); - hostSettingsTable.Columns.Add("SettingValue"); - hostSettingsTable.Columns.Add("SettingIsSecure"); - hostSettingsTable.PrimaryKey = new[] { nameCol }; - - hostSettingsTable.Rows.Add("PerformanceSetting", "0", false); - this._mockData.Setup(c => c.GetHostSettings()).Returns(hostSettingsTable.CreateDataReader()); - } - - [TearDown] - public void TearDown() - { - MockComponentProvider.ResetContainer(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_Constructor_Throws_On_Null_DataService() - { - // Arrange - var mockPortalController = new Mock(); - - // Act, Assert - new PortalGroupController(null, mockPortalController.Object); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_Constructor_Throws_On_Null_PortalController() - { - // Arrange - var mockDataService = new Mock(); - - // Act, Assert - new PortalGroupController(mockDataService.Object, null); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_AddPortalToGroup_Throws_On_Null_PortalGroup() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; - - // Act, Assert - controller.AddPortalToGroup(portal, null, this.userCopied); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_AddPortalToGroup_Throws_On_Null_Portal() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - var portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - - // Act, Assert - controller.AddPortalToGroup(null, portalGroup, this.userCopied); - } - - [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException))] - public void PortalGroupController_AddPortalToGroup_Throws_On_Negative_PortalGroupId() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; - - PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = -1 }; - - // Act, Assert - controller.AddPortalToGroup(portal, portalGroup, this.userCopied); - } - - [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException))] - public void PortalGroupController_AddPortalToGroup_Throws_On_Negative_PortalId() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - var portal = new PortalInfo { PortalID = -1 }; - - PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - - // Act, Assert - controller.AddPortalToGroup(portal, portalGroup, this.userCopied); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_AddPortalGroup_Throws_On_Null_PortalGroup() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - // Act, Assert - controller.AddPortalGroup(null); - } - - [Test] - public void PortalGroupController_AddPortalGroup_Calls_DataService_On_Valid_Arguments() - { - // Arrange - MockComponentProvider.CreateNew(); - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - PortalGroupInfo portalGroup = CreateValidPortalGroup(); - portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; - - // Act - controller.AddPortalGroup(portalGroup); - - // Assert - mockDataService.Verify(ds => ds.AddPortalGroup(portalGroup, It.IsAny())); - } - - [Test] - public void PortalGroupController_AddPortalGroup_Calls_PortalController_On_Valid_Arguments() - { - // Arrange - MockComponentProvider.CreateNew(); - var mockDataService = new Mock(); - var masterPortal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; - var mockPortalController = new Mock(); - mockPortalController.Setup(pc => pc.GetPortal(Constants.PORTAL_ValidPortalId)) - .Returns(masterPortal); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - PortalGroupInfo portalGroup = CreateValidPortalGroup(); - portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; - - // Act - controller.AddPortalGroup(portalGroup); - - // Assert - mockPortalController.Verify(pc => pc.GetPortal(portalGroup.MasterPortalId)); - mockPortalController.Verify(pc => pc.UpdatePortalInfo(masterPortal)); - } - - [Test] - public void PortalGroupController_AddPortalGroup_Returns_ValidId_On_Valid_PortalGroup() - { - // Arrange - MockComponentProvider.CreateNew(); - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.AddPortalGroup(It.IsAny(), It.IsAny())).Returns(Constants.PORTALGROUP_AddPortalGroupId); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - PortalGroupInfo portalGroup = CreateValidPortalGroup(); - portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; - - // Act - int portalGroupId = controller.AddPortalGroup(portalGroup); - - // Assert - Assert.AreEqual(Constants.PORTALGROUP_AddPortalGroupId, portalGroupId); - } - - [Test] - public void PortalGroupController_AddPortalGroup_Sets_PortalGroupId_Property_On_Valid_PortalGroup() - { - // Arrange - MockComponentProvider.CreateNew(); - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.AddPortalGroup(It.IsAny(), It.IsAny())).Returns(Constants.PORTALGROUP_AddPortalGroupId); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - PortalGroupInfo portalGroup = CreateValidPortalGroup(); - portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; - - // Act - controller.AddPortalGroup(portalGroup); - - // Assert - Assert.AreEqual(Constants.PORTALGROUP_AddPortalGroupId, portalGroup.PortalGroupId); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_DeletePortalGroup_Throws_On_Null_PortalGroup() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - // Act, Assert - controller.DeletePortalGroup(null); - } - - [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException))] - public void PortalGroupController_DeletePortalGroup_Throws_On_Negative_PortalGroupId() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - PortalGroupInfo portalGroup = CreateValidPortalGroup(); - portalGroup.PortalGroupId = Null.NullInteger; - - // Act, Assert - controller.DeletePortalGroup(portalGroup); - } - - [Test] - public void PortalGroupController_DeletePortalGroup_Calls_DataService_On_Valid_PortalGroupId() - { - // Arrange - MockComponentProvider.CreateNew(); - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - PortalGroupInfo portalGroup = CreateValidPortalGroup(); - portalGroup.PortalGroupId = Constants.PORTALGROUP_DeletePortalGroupId; - - // Act - controller.DeletePortalGroup(portalGroup); - - // Assert - mockDataService.Verify(ds => ds.DeletePortalGroup(portalGroup)); - } - - [Test] - - public void PortalGroupController_GetPortalGroups_Calls_DataService() - { - // Arrange - var mockCache = MockComponentProvider.CreateNew(); - mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); - - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader(0, Constants.USER_ValidId)); - - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - // Act - controller.GetPortalGroups(); - - // Assert - mockDataService.Verify(ds => ds.GetPortalGroups()); - } - - [Test] - public void PortalGroupController_GetPortalGroups_Returns_EmptyList_If_No_Items() - { - // Arrange - var mockCache = MockComponentProvider.CreateNew(); - mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); - - Mock mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader(0, Constants.USER_ValidId)); - - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - // Act - IEnumerable portalGroups = controller.GetPortalGroups(); - - // Assert - Assert.AreEqual(0, portalGroups.Count()); - } - - [Test] - public void PortalGroupController_GetPortalGroups_Returns_List_Of_PortalGroups() - { - // Arrange - var mockCache = MockComponentProvider.CreateNew(); - mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); - - Mock mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader( - Constants.PORTALGROUP_ValidPortalGroupCount, - Constants.USER_ValidId)); - - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - // Act - IEnumerable portalGroups = controller.GetPortalGroups(); - - // Assert - Assert.AreEqual(Constants.PORTALGROUP_ValidPortalGroupCount, portalGroups.Count()); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_RemovePortalFromGroup_Throws_On_Null_PortalGroup() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; - - // Act, Assert - controller.RemovePortalFromGroup(portal, null, false, this.userCopied); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_RemovePortalFromGroup_Throws_On_Null_Portal() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - var portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - - // Act, Assert - controller.RemovePortalFromGroup(null, portalGroup, false, this.userCopied); - } - - [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException))] - public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_PortalGroupId() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; - - PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = -1 }; - - // Act, Assert - controller.RemovePortalFromGroup(portal, portalGroup, false, this.userCopied); - } - - [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException))] - public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_PortalId() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - var portal = new PortalInfo { PortalID = -1 }; - - PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - - // Act, Assert - controller.RemovePortalFromGroup(portal, portalGroup, false, this.userCopied); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void PortalGroupController_UpdatePortalGroup_Throws_On_Null_PortalGroup() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - // Act, Assert - controller.UpdatePortalGroup(null); - } - - [Test] - public void PortalGroupController_UpdatePortalGroup_Throws_On_Negative_PortalGroupId() - { - // Arrange - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - var portalGroup = new PortalGroupInfo(); - portalGroup.PortalGroupId = Null.NullInteger; - - Assert.Throws(() => controller.UpdatePortalGroup(portalGroup)); - } - - [Test] - public void PortalGroupController_UpdatePortalGroup_Calls_DataService_On_Valid_PortalGroup() - { - // Arrange - MockComponentProvider.CreateNew(); - var mockDataService = new Mock(); - var mockPortalController = new Mock(); - var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - - var portalGroup = CreateValidPortalGroup(); - portalGroup.PortalGroupId = Constants.PORTALGROUP_UpdatePortalGroupId; - portalGroup.PortalGroupName = Constants.PORTALGROUP_UpdateName; - portalGroup.PortalGroupDescription = Constants.PORTALGROUP_UpdateDescription; - - // Act - controller.UpdatePortalGroup(portalGroup); - - // Assert - mockDataService.Verify(ds => ds.UpdatePortalGroup(portalGroup, It.IsAny())); - } - - private static DataTable CreatePortalGroupTable() - { - // Create Categories table. - DataTable table = new DataTable(); - - // Create columns, ID and Name. - DataColumn idColumn = table.Columns.Add("PortalGroupID", typeof(int)); - table.Columns.Add("MasterPortalID", typeof(int)); - table.Columns.Add("PortalGroupName", typeof(string)); - table.Columns.Add("PortalGroupDescription", typeof(string)); - table.Columns.Add("AuthenticationDomain", typeof(string)); - table.Columns.Add("CreatedByUserID", typeof(int)); - table.Columns.Add("CreatedOnDate", typeof(DateTime)); - table.Columns.Add("LastModifiedByUserID", typeof(int)); - table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - // Set the ID column as the primary key column. - table.PrimaryKey = new[] { idColumn }; - - return table; - } - - private static string GetName(int i) - { - return string.Format(string.Format(Constants.PORTALGROUP_ValidNameFormat, i)); - } - - private static string GetDescription(int i) - { - return string.Format(string.Format(Constants.PORTALGROUP_ValidDescriptionFormat, i)); - } - - private static PortalGroupInfo CreateValidPortalGroup() - { - var portalGroup = new PortalGroupInfo - { - PortalGroupName = Constants.PORTALGROUP_ValidName, - PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, - MasterPortalId = Constants.PORTAL_ValidPortalId, - }; - return portalGroup; - } - - private static IDataReader CreateValidPortalGroupsReader(int count, int startUserId) - { - DataTable table = CreatePortalGroupTable(); - for (int i = Constants.PORTALGROUP_ValidPortalGroupId; i < Constants.PORTALGROUP_ValidPortalGroupId + count; i++) - { - string name = (count == 1) ? Constants.PORTALGROUP_ValidName : GetName(i); - string description = (count == 1) ? Constants.PORTALGROUP_ValidDescription : GetDescription(i); - const string domain = "mydomain.com"; - int userId = (startUserId == Null.NullInteger) ? Constants.USER_ValidId + i : startUserId; - - table.Rows.Add(new object[] - { - i, - -1, - name, - description, - domain, - userId, - }); - } - - return table.CreateDataReader(); - } - } - - // ReSharper restore InconsistentNaming -} +namespace DotNetNuke.Tests.Core.Controllers.Portal +{ + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Portals.Data; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + // ReSharper disable InconsistentNaming + [TestFixture] + public class PortalGroupControllerTests + { + private Mock mockData; +#pragma warning disable 649 + private UserCopiedCallback userCopied; +#pragma warning restore 649 + + [SetUp] + public void SetUp() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + this.mockData = MockComponentProvider.CreateDataProvider(); + DataTable hostSettingsTable = new DataTable("HostSettings"); + + var nameCol = hostSettingsTable.Columns.Add("SettingName"); + hostSettingsTable.Columns.Add("SettingValue"); + hostSettingsTable.Columns.Add("SettingIsSecure"); + hostSettingsTable.PrimaryKey = new[] { nameCol }; + + hostSettingsTable.Rows.Add("PerformanceSetting", "0", false); + this.mockData.Setup(c => c.GetHostSettings()).Returns(hostSettingsTable.CreateDataReader()); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + MockComponentProvider.ResetContainer(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_Constructor_Throws_On_Null_DataService() + { + // Arrange + var mockPortalController = new Mock(); + + // Act, Assert + new PortalGroupController(null, mockPortalController.Object); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_Constructor_Throws_On_Null_PortalController() + { + // Arrange + var mockDataService = new Mock(); + + // Act, Assert + new PortalGroupController(mockDataService.Object, null); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_AddPortalToGroup_Throws_On_Null_PortalGroup() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; + + // Act, Assert + controller.AddPortalToGroup(portal, null, this.userCopied); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_AddPortalToGroup_Throws_On_Null_Portal() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + var portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; + + // Act, Assert + controller.AddPortalToGroup(null, portalGroup, this.userCopied); + } + + [Test] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void PortalGroupController_AddPortalToGroup_Throws_On_Negative_PortalGroupId() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; + + PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = -1 }; + + // Act, Assert + controller.AddPortalToGroup(portal, portalGroup, this.userCopied); + } + + [Test] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void PortalGroupController_AddPortalToGroup_Throws_On_Negative_PortalId() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + var portal = new PortalInfo { PortalID = -1 }; + + PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; + + // Act, Assert + controller.AddPortalToGroup(portal, portalGroup, this.userCopied); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_AddPortalGroup_Throws_On_Null_PortalGroup() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + // Act, Assert + controller.AddPortalGroup(null); + } + + [Test] + public void PortalGroupController_AddPortalGroup_Calls_DataService_On_Valid_Arguments() + { + // Arrange + MockComponentProvider.CreateNew(); + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + PortalGroupInfo portalGroup = CreateValidPortalGroup(); + portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; + + // Act + controller.AddPortalGroup(portalGroup); + + // Assert + mockDataService.Verify(ds => ds.AddPortalGroup(portalGroup, It.IsAny())); + } + + [Test] + public void PortalGroupController_AddPortalGroup_Calls_PortalController_On_Valid_Arguments() + { + // Arrange + MockComponentProvider.CreateNew(); + var mockDataService = new Mock(); + var masterPortal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; + var mockPortalController = new Mock(); + mockPortalController.Setup(pc => pc.GetPortal(Constants.PORTAL_ValidPortalId)) + .Returns(masterPortal); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + PortalGroupInfo portalGroup = CreateValidPortalGroup(); + portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; + + // Act + controller.AddPortalGroup(portalGroup); + + // Assert + mockPortalController.Verify(pc => pc.GetPortal(portalGroup.MasterPortalId)); + mockPortalController.Verify(pc => pc.UpdatePortalInfo(masterPortal)); + } + + [Test] + public void PortalGroupController_AddPortalGroup_Returns_ValidId_On_Valid_PortalGroup() + { + // Arrange + MockComponentProvider.CreateNew(); + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.AddPortalGroup(It.IsAny(), It.IsAny())).Returns(Constants.PORTALGROUP_AddPortalGroupId); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + PortalGroupInfo portalGroup = CreateValidPortalGroup(); + portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; + + // Act + int portalGroupId = controller.AddPortalGroup(portalGroup); + + // Assert + Assert.AreEqual(Constants.PORTALGROUP_AddPortalGroupId, portalGroupId); + } + + [Test] + public void PortalGroupController_AddPortalGroup_Sets_PortalGroupId_Property_On_Valid_PortalGroup() + { + // Arrange + MockComponentProvider.CreateNew(); + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.AddPortalGroup(It.IsAny(), It.IsAny())).Returns(Constants.PORTALGROUP_AddPortalGroupId); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + PortalGroupInfo portalGroup = CreateValidPortalGroup(); + portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; + + // Act + controller.AddPortalGroup(portalGroup); + + // Assert + Assert.AreEqual(Constants.PORTALGROUP_AddPortalGroupId, portalGroup.PortalGroupId); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_DeletePortalGroup_Throws_On_Null_PortalGroup() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + // Act, Assert + controller.DeletePortalGroup(null); + } + + [Test] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void PortalGroupController_DeletePortalGroup_Throws_On_Negative_PortalGroupId() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + PortalGroupInfo portalGroup = CreateValidPortalGroup(); + portalGroup.PortalGroupId = Null.NullInteger; + + // Act, Assert + controller.DeletePortalGroup(portalGroup); + } + + [Test] + public void PortalGroupController_DeletePortalGroup_Calls_DataService_On_Valid_PortalGroupId() + { + // Arrange + MockComponentProvider.CreateNew(); + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + PortalGroupInfo portalGroup = CreateValidPortalGroup(); + portalGroup.PortalGroupId = Constants.PORTALGROUP_DeletePortalGroupId; + + // Act + controller.DeletePortalGroup(portalGroup); + + // Assert + mockDataService.Verify(ds => ds.DeletePortalGroup(portalGroup)); + } + + [Test] + + public void PortalGroupController_GetPortalGroups_Calls_DataService() + { + // Arrange + var mockCache = MockComponentProvider.CreateNew(); + mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); + + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader(0, Constants.USER_ValidId)); + + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + // Act + controller.GetPortalGroups(); + + // Assert + mockDataService.Verify(ds => ds.GetPortalGroups()); + } + + [Test] + public void PortalGroupController_GetPortalGroups_Returns_EmptyList_If_No_Items() + { + // Arrange + var mockCache = MockComponentProvider.CreateNew(); + mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); + + Mock mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader(0, Constants.USER_ValidId)); + + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + // Act + IEnumerable portalGroups = controller.GetPortalGroups(); + + // Assert + Assert.AreEqual(0, portalGroups.Count()); + } + + [Test] + public void PortalGroupController_GetPortalGroups_Returns_List_Of_PortalGroups() + { + // Arrange + var mockCache = MockComponentProvider.CreateNew(); + mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); + + Mock mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader( + Constants.PORTALGROUP_ValidPortalGroupCount, + Constants.USER_ValidId)); + + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + // Act + IEnumerable portalGroups = controller.GetPortalGroups(); + + // Assert + Assert.AreEqual(Constants.PORTALGROUP_ValidPortalGroupCount, portalGroups.Count()); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_RemovePortalFromGroup_Throws_On_Null_PortalGroup() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; + + // Act, Assert + controller.RemovePortalFromGroup(portal, null, false, this.userCopied); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_RemovePortalFromGroup_Throws_On_Null_Portal() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + var portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; + + // Act, Assert + controller.RemovePortalFromGroup(null, portalGroup, false, this.userCopied); + } + + [Test] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_PortalGroupId() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; + + PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = -1 }; + + // Act, Assert + controller.RemovePortalFromGroup(portal, portalGroup, false, this.userCopied); + } + + [Test] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_PortalId() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + var portal = new PortalInfo { PortalID = -1 }; + + PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; + + // Act, Assert + controller.RemovePortalFromGroup(portal, portalGroup, false, this.userCopied); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void PortalGroupController_UpdatePortalGroup_Throws_On_Null_PortalGroup() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + // Act, Assert + controller.UpdatePortalGroup(null); + } + + [Test] + public void PortalGroupController_UpdatePortalGroup_Throws_On_Negative_PortalGroupId() + { + // Arrange + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + var portalGroup = new PortalGroupInfo(); + portalGroup.PortalGroupId = Null.NullInteger; + + Assert.Throws(() => controller.UpdatePortalGroup(portalGroup)); + } + + [Test] + public void PortalGroupController_UpdatePortalGroup_Calls_DataService_On_Valid_PortalGroup() + { + // Arrange + MockComponentProvider.CreateNew(); + var mockDataService = new Mock(); + var mockPortalController = new Mock(); + var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); + + var portalGroup = CreateValidPortalGroup(); + portalGroup.PortalGroupId = Constants.PORTALGROUP_UpdatePortalGroupId; + portalGroup.PortalGroupName = Constants.PORTALGROUP_UpdateName; + portalGroup.PortalGroupDescription = Constants.PORTALGROUP_UpdateDescription; + + // Act + controller.UpdatePortalGroup(portalGroup); + + // Assert + mockDataService.Verify(ds => ds.UpdatePortalGroup(portalGroup, It.IsAny())); + } + + private static DataTable CreatePortalGroupTable() + { + // Create Categories table. + DataTable table = new DataTable(); + + // Create columns, ID and Name. + DataColumn idColumn = table.Columns.Add("PortalGroupID", typeof(int)); + table.Columns.Add("MasterPortalID", typeof(int)); + table.Columns.Add("PortalGroupName", typeof(string)); + table.Columns.Add("PortalGroupDescription", typeof(string)); + table.Columns.Add("AuthenticationDomain", typeof(string)); + table.Columns.Add("CreatedByUserID", typeof(int)); + table.Columns.Add("CreatedOnDate", typeof(DateTime)); + table.Columns.Add("LastModifiedByUserID", typeof(int)); + table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + + // Set the ID column as the primary key column. + table.PrimaryKey = new[] { idColumn }; + + return table; + } + + private static string GetName(int i) + { + return string.Format(string.Format(Constants.PORTALGROUP_ValidNameFormat, i)); + } + + private static string GetDescription(int i) + { + return string.Format(string.Format(Constants.PORTALGROUP_ValidDescriptionFormat, i)); + } + + private static PortalGroupInfo CreateValidPortalGroup() + { + var portalGroup = new PortalGroupInfo + { + PortalGroupName = Constants.PORTALGROUP_ValidName, + PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, + MasterPortalId = Constants.PORTAL_ValidPortalId, + }; + return portalGroup; + } + + private static IDataReader CreateValidPortalGroupsReader(int count, int startUserId) + { + DataTable table = CreatePortalGroupTable(); + for (int i = Constants.PORTALGROUP_ValidPortalGroupId; i < Constants.PORTALGROUP_ValidPortalGroupId + count; i++) + { + string name = (count == 1) ? Constants.PORTALGROUP_ValidName : GetName(i); + string description = (count == 1) ? Constants.PORTALGROUP_ValidDescription : GetDescription(i); + const string domain = "mydomain.com"; + int userId = (startUserId == Null.NullInteger) ? Constants.USER_ValidId + i : startUserId; + + table.Rows.Add(new object[] + { + i, + -1, + name, + description, + domain, + userId, + }); + } + + return table.CreateDataReader(); + } + } + + // ReSharper restore InconsistentNaming +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs index 709036f7cdb..2d9d7d85549 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs @@ -2,747 +2,754 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Controllers.Search -{ - using System; - using System.Collections.Generic; - using System.Data; - using System.IO; +namespace DotNetNuke.Tests.Core.Controllers.Search +{ + using System; + using System.Collections.Generic; + using System.Data; + using System.IO; using System.Threading; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.ComponentModel; - using DotNetNuke.Data; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Users; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.Localization; - using DotNetNuke.Services.Search.Entities; - using DotNetNuke.Services.Search.Internals; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; using DotNetNuke.Tests.Utilities.Mocks; + using Microsoft.Extensions.DependencyInjection; - using Moq; - using NUnit.Framework; - - /// - /// Testing various aspects of SearchController. - /// - [TestFixture] - public class InternalSearchControllerTests + + using Moq; + + using NUnit.Framework; + + /// + /// Testing various aspects of SearchController. + /// + [TestFixture] + public class InternalSearchControllerTests { - private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; - private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; - private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; - - private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; - private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; - private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; - - private const int PortalId0 = 0; - private const int PortalId1 = 1; - - private const string TermDNN = "DNN"; - private const string TermDotNetNuke = "DotnetNuke"; - private const string TermLaptop = "Laptop"; - private const string TermNotebook = "Notebook"; - private const string TermJump = "Jump"; - private const string TermLeap = "Leap"; - private const string TermHop = "Hop"; - - private const string ModuleSearchTypeName = "module"; - private const string OtherSearchTypeName = "other"; - private const string TabSearchTypeName = "tab"; - private const string DocumentSearchTypeName = "document"; - private const string UrlSearchTypeName = "url"; - private const string ModuleResultControllerClass = "DotNetNuke.Services.Search.Crawlers.ModuleResultController, DotNetNuke"; - private const string FakeResultControllerClass = "DotNetNuke.Tests.Core.Controllers.Search.FakeResultController, DotNetNuke.Tests.Core"; - - private const string NoPermissionFakeResultControllerClass = - "DotNetNuke.Tests.Core.Controllers.Search.NoPermissionFakeResultController, DotNetNuke.Tests.Core"; - - private const string CultureEnUs = "en-US"; - private const string CultureEnCa = "en-CA"; - private const string CultureItIt = "it-IT"; - private const string CultureEsEs = "es-ES"; - private const int LanguageIdEnUs = 1; - private const int LanguageIdEnFr = 2; - private const int LanguageIdItIt = 3; - private const int LanguageIdEsEs = 4; - - private const string SearchIndexFolder = @"App_Data\InternalSearchTests"; - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - private Mock _mockHostController; - private Mock _mockCachingProvider; - private Mock _mockDataProvider; - private Mock _mockLocaleController; - private Mock _mockSearchHelper; - private Mock _mockUserController; - - private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; - - public enum SearchTypeIds - { - ModuleSearchTypeId = 1, - TabSearchTypeId, - DocumentSearchTypeId, - UrlSearchTypeId, - OtherSearchTypeId, - UnknownSearchTypeId, - } - - [SetUp] - public void SetUp() - { - ComponentFactory.Container = new SimpleContainer(); - MockComponentProvider.ResetContainer(); - - var serviceCollection = new ServiceCollection(); - serviceCollection.AddTransient(container => Mock.Of()); - serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - this._mockDataProvider = MockComponentProvider.CreateDataProvider(); - this._mockLocaleController = MockComponentProvider.CreateLocaleController(); - this._mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - - this._mockUserController = new Mock(); - this._mockHostController = new Mock(); - this._mockSearchHelper = new Mock(); - - this.SetupDataProvider(); - this.SetupHostController(); - this.SetupSearchHelper(); - this.SetupLocaleController(); - - this._mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())) - .Returns((int portalId, int userId) => this.GetUserByIdCallback(portalId, userId)); - UserController.SetTestableInstance(this._mockUserController.Object); - - this.CreateNewLuceneControllerInstance(); - } - - [TearDown] - public void TearDown() - { - this._luceneController.Dispose(); - this.DeleteIndexFolder(); - InternalSearchController.ClearInstance(); - UserController.ClearInstance(); - SearchHelper.ClearInstance(); - LuceneController.ClearInstance(); - this._luceneController = null; - Globals.DependencyProvider = null; - } - - [Test] - public void SearchController_Add_Throws_On_Null_SearchDocument() - { - // Arrange - - // Act, Assert - Assert.Throws(() => this._internalSearchController.AddSearchDocument(null)); - } - - [Test] - public void SearchController_Add_Throws_On_Null_Or_Empty_UniqueuKey() - { - // Arrange - - // Act, Assert - Assert.Throws(() => this._internalSearchController.AddSearchDocument(new SearchDocument())); - } - - [Test] - public void SearchController_Add_Throws_On_Null_OrEmpty_Title() - { - // Arrange - - // Act, Assert - Assert.Throws( - () => this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString() })); - } - - [Test] - public void SearchController_AddSearchDcoumets_Does_Not_Throw_On_Null_OrEmpty_Title() - { - // Arrange - var documents = new List { new SearchDocument { UniqueKey = Guid.NewGuid().ToString() } }; - - // Act, Assert - this._internalSearchController.AddSearchDocuments(documents); - } - - [Test] - public void SearchController_AddSearchDcoumets_Does_Not_Throw_On_Empty_Search_Document() - { - // Arrange - var documents = new List { new SearchDocument() }; - - // Act, Assert - this._internalSearchController.AddSearchDocuments(documents); - } - - [Test] - public void SearchController_Add_Throws_On_Zero_SearchTypeId() - { - // Arrange - - // Act, Assert - Assert.Throws( - () => this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString() })); - } - - [Test] - public void SearchController_Add_Throws_On_Negative_SearchTypeId() - { - // Arrange - - // Act, Assert - Assert.Throws( - () => - this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = -1 })); - } - - [Test] - public void SearchController_Add_Throws_On_DateTimeMin_ModifiedTimeUtc() - { - // Arrange - - // Act, Assert - Assert.Throws( - () => this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = 1 })); - } - - [Test] - public void SearchController_Add_Then_Delete_ModuleDefinition_WorksAsExpected() - { - // Arrange - const int totalDocs = 10; - var now = DateTime.UtcNow; - - // Act - for (var i = 1; i <= totalDocs; i++) - { - var doc = new SearchDocument - { - ModuleDefId = i, - ModuleId = 100, - SearchTypeId = ModuleSearchTypeId, - PortalId = PortalId0, - UniqueKey = Guid.NewGuid().ToString(), - ModifiedTimeUtc = now, - }; - - this._internalSearchController.AddSearchDocument(doc); - } - - // Assert - var stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - - // Act - delete last item - var searchDoc = new SearchDocument { ModuleDefId = totalDocs }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); - Assert.AreEqual(1, stats.TotalDeletedDocuments); - - // Act - delete first item - searchDoc = new SearchDocument { ModuleDefId = 1 }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); - Assert.AreEqual(2, stats.TotalDeletedDocuments); - } - - [Test] - public void SearchController_Add_Then_Delete_Module_WorksAsExpected() - { - // Arrange - const int totalDocs = 10; - var now = DateTime.UtcNow; - - // Act - for (var i = 1; i <= totalDocs; i++) - { - var doc = new SearchDocument - { - ModuleId = i, - ModuleDefId = 10, - PortalId = PortalId0, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = ModuleSearchTypeId, - ModifiedTimeUtc = now, - }; - - this._internalSearchController.AddSearchDocument(doc); - } - - // Assert - var stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - - // Act - delete last item - var searchDoc = new SearchDocument { ModuleId = totalDocs }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); - Assert.AreEqual(1, stats.TotalDeletedDocuments); - - // Act - delete first item - searchDoc = new SearchDocument { ModuleId = 1 }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); - Assert.AreEqual(2, stats.TotalDeletedDocuments); - } - - [Test] - public void SearchController_Add_Then_Delete_Portals_WorksAsExpected() - { - // Arrange - const int totalDocs = 10; // must be even - var now = DateTime.UtcNow; - - // Act - for (var i = 1; i <= totalDocs; i++) - { - var doc = new SearchDocument - { - PortalId = i <= (totalDocs / 2) ? PortalId0 : PortalId1, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = ModuleSearchTypeId, - ModifiedTimeUtc = now, - ModuleId = 100, - ModuleDefId = 10, - }; - - this._internalSearchController.AddSearchDocument(doc); - } - - // Assert - var stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - - // Act - delete all portal 1 items - var searchDoc = new SearchDocument { PortalId = PortalId1 }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - delete all portal 1 - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs / 2, stats.TotalActiveDocuments); - Assert.AreEqual(totalDocs / 2, stats.TotalDeletedDocuments); - } - - [Test] - public void SearchController_Add_Then_Delete_Roles_WorksAsExpected() - { - // Arrange - const int totalDocs = 10; - var now = DateTime.UtcNow; - - // Act - for (var i = 1; i <= totalDocs; i++) - { - var doc = new SearchDocument - { - RoleId = i, - PortalId = PortalId0, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = ModuleSearchTypeId, - ModifiedTimeUtc = now, - ModuleId = 100, - ModuleDefId = 10, - }; - - this._internalSearchController.AddSearchDocument(doc); - } - - // Assert - var stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - - // Act - delete last item - var searchDoc = new SearchDocument { RoleId = totalDocs }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); - Assert.AreEqual(1, stats.TotalDeletedDocuments); - - // Act - delete first item - searchDoc = new SearchDocument { RoleId = 1 }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); - Assert.AreEqual(2, stats.TotalDeletedDocuments); - } - - [Test] - public void SearchController_Add_Then_Delete_Tabs_WorksAsExpected() - { - // Arrange - const int totalDocs = 10; - var now = DateTime.UtcNow; - - // Act - for (var i = 1; i <= totalDocs; i++) - { - var doc = new SearchDocument - { - TabId = i, - PortalId = PortalId0, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = TabSearchTypeId, - ModifiedTimeUtc = now, - }; - - this._internalSearchController.AddSearchDocument(doc); - } - - // Assert - var stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - - // Act - delete last item - var searchDoc = new SearchDocument { TabId = totalDocs }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); - Assert.AreEqual(1, stats.TotalDeletedDocuments); - - // Act - delete first item - searchDoc = new SearchDocument { TabId = 1 }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); - Assert.AreEqual(2, stats.TotalDeletedDocuments); - } - - [Test] - public void SearchController_Add_Then_Delete_Users_WorksAsExpected() - { - // Arrange - const int totalDocs = 10; - var now = DateTime.UtcNow; - - // Act - for (var i = 1; i <= totalDocs; i++) - { - var doc = new SearchDocument - { - AuthorUserId = i, - PortalId = PortalId0, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = ModuleSearchTypeId, - ModifiedTimeUtc = now, - ModuleId = 100, - ModuleDefId = 10, - }; - - this._internalSearchController.AddSearchDocument(doc); - } - - // Assert - var stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - - // Act - delete last item - var searchDoc = new SearchDocument { AuthorUserId = totalDocs }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); - Assert.AreEqual(1, stats.TotalDeletedDocuments); - - // Act - delete first item - searchDoc = new SearchDocument { AuthorUserId = 1 }; - this._internalSearchController.DeleteSearchDocument(searchDoc); - - // Assert - stats = this.GetSearchStatistics(); - Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); - Assert.AreEqual(2, stats.TotalDeletedDocuments); - } - - private void CreateNewLuceneControllerInstance() - { - this.DeleteIndexFolder(); - InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); - this._internalSearchController = InternalSearchController.Instance; - - if (this._luceneController != null) - { - LuceneController.ClearInstance(); - this._luceneController.Dispose(); - } - - this._luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(this._luceneController); - } - - private void SetupHostController() - { - this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); - this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())) - .Returns(Constants.DefaultSearchDescriptionBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); - HostController.RegisterInstance(this._mockHostController.Object); - } - - private void SetupLocaleController() - { - this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); - - this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); - } - - private void SetupDataProvider() - { - // Standard DataProvider Path for Logging - this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - - DataTableReader searchTypes = null; - this._mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) - .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) - .Returns(() => searchTypes); - - this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); - } - - private IDataReader GetPortalsCallBack(string culture) - { - return this.GetPortalCallBack(PortalId0, CultureEnUs); - } - - private IDataReader GetPortalCallBack(int portalId, string culture) - { - var table = new DataTable("Portal"); - - var cols = new[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", - "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", - "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", - "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", - "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - const int homePage = 1; - table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, - "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, - "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", - null, homePage.ToString("D"), null, null, "57", "56", "-1", "-1", "7", null, null, "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); - - return table.CreateDataReader(); - } - - private void SetupSearchHelper() - { - this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); - this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(this.GetSynonymsCallBack); - this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())) - .Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); - this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); - this._mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); - this._mockSearchHelper.Setup(c => c.GetSynonymsGroups(It.IsAny(), It.IsAny())).Returns(this.GetSynonymsGroupsCallBack); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( - new SearchStopWords - { - PortalId = 0, - CultureCode = CultureEsEs, - StopWords = "los,de,el", - }); - this._mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(new SearchHelperImpl().RephraseSearchText); - this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); - SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); - } - - private IList GetSynonymsGroupsCallBack() - { - var groups = new List - { - new SynonymsGroup { PortalId = 0, SynonymsGroupId = 1, SynonymsTags = string.Join(",", TermDNN, TermDotNetNuke) }, - new SynonymsGroup { PortalId = 0, SynonymsGroupId = 2, SynonymsTags = string.Join(",", TermLaptop, TermNotebook) }, - new SynonymsGroup { PortalId = 0, SynonymsGroupId = 3, SynonymsTags = string.Join(",", TermJump, TermLeap, TermHop) }, - }; - - return groups; - } - - private SearchType GetSearchTypeByNameCallback(string searchTypeName) - { - var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; - switch (searchTypeName) - { - case ModuleSearchTypeName: - searchType.SearchTypeId = ModuleSearchTypeId; - break; - case TabSearchTypeName: - searchType.SearchTypeId = TabSearchTypeId; - break; - case OtherSearchTypeName: - searchType.SearchTypeId = OtherSearchTypeId; - break; - case DocumentSearchTypeName: - searchType.SearchTypeId = DocumentSearchTypeId; - break; - case UrlSearchTypeName: - searchType.SearchTypeId = UrlSearchTypeId; - break; - } - - return searchType; - } - - private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) - { - var synonyms = new List(); + private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; + private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; + private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; + + private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; + private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; + private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; + + private const int PortalId0 = 0; + private const int PortalId1 = 1; + + private const string TermDNN = "DNN"; + private const string TermDotNetNuke = "DotnetNuke"; + private const string TermLaptop = "Laptop"; + private const string TermNotebook = "Notebook"; + private const string TermJump = "Jump"; + private const string TermLeap = "Leap"; + private const string TermHop = "Hop"; + + private const string ModuleSearchTypeName = "module"; + private const string OtherSearchTypeName = "other"; + private const string TabSearchTypeName = "tab"; + private const string DocumentSearchTypeName = "document"; + private const string UrlSearchTypeName = "url"; + private const string ModuleResultControllerClass = "DotNetNuke.Services.Search.Crawlers.ModuleResultController, DotNetNuke"; + private const string FakeResultControllerClass = "DotNetNuke.Tests.Core.Controllers.Search.FakeResultController, DotNetNuke.Tests.Core"; + + private const string NoPermissionFakeResultControllerClass = + "DotNetNuke.Tests.Core.Controllers.Search.NoPermissionFakeResultController, DotNetNuke.Tests.Core"; + + private const string CultureEnUs = "en-US"; + private const string CultureEnCa = "en-CA"; + private const string CultureItIt = "it-IT"; + private const string CultureEsEs = "es-ES"; + private const int LanguageIdEnUs = 1; + private const int LanguageIdEnFr = 2; + private const int LanguageIdItIt = 3; + private const int LanguageIdEsEs = 4; + + private const string SearchIndexFolder = @"App_Data\InternalSearchTests"; + private readonly double readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; + private Mock mockHostController; + private Mock mockCachingProvider; + private Mock mockDataProvider; + private Mock mockLocaleController; + private Mock mockSearchHelper; + private Mock mockUserController; + + private IInternalSearchController internalSearchController; + private LuceneControllerImpl luceneController; + + public enum SearchTypeIds + { + ModuleSearchTypeId = 1, + TabSearchTypeId, + DocumentSearchTypeId, + UrlSearchTypeId, + OtherSearchTypeId, + UnknownSearchTypeId, + } + + [SetUp] + public void SetUp() + { + ComponentFactory.Container = new SimpleContainer(); + MockComponentProvider.ResetContainer(); + + this.mockHostController = new Mock(); + this.SetupHostController(); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); + serviceCollection.AddTransient(container => (IHostSettingsService)this.mockHostController.Object); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + this.mockDataProvider = MockComponentProvider.CreateDataProvider(); + this.mockLocaleController = MockComponentProvider.CreateLocaleController(); + this.mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); + this.mockUserController = new Mock(); + + this.mockSearchHelper = new Mock(); + this.SetupDataProvider(); + this.SetupSearchHelper(); + this.SetupLocaleController(); + + this.mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())) + .Returns((int portalId, int userId) => this.GetUserByIdCallback(portalId, userId)); + UserController.SetTestableInstance(this.mockUserController.Object); + + this.CreateNewLuceneControllerInstance(); + } + + [TearDown] + public void TearDown() + { + this.mockHostController = null; + Globals.DependencyProvider = null; + this.luceneController.Dispose(); + this.DeleteIndexFolder(); + InternalSearchController.ClearInstance(); + UserController.ClearInstance(); + SearchHelper.ClearInstance(); + LuceneController.ClearInstance(); + this.luceneController = null; + Globals.DependencyProvider = null; + } + + [Test] + public void SearchController_Add_Throws_On_Null_SearchDocument() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this.internalSearchController.AddSearchDocument(null)); + } + + [Test] + public void SearchController_Add_Throws_On_Null_Or_Empty_UniqueuKey() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this.internalSearchController.AddSearchDocument(new SearchDocument())); + } + + [Test] + public void SearchController_Add_Throws_On_Null_OrEmpty_Title() + { + // Arrange + + // Act, Assert + Assert.Throws( + () => this.internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString() })); + } + + [Test] + public void SearchController_AddSearchDcoumets_Does_Not_Throw_On_Null_OrEmpty_Title() + { + // Arrange + var documents = new List { new SearchDocument { UniqueKey = Guid.NewGuid().ToString() } }; + + // Act, Assert + this.internalSearchController.AddSearchDocuments(documents); + } + + [Test] + public void SearchController_AddSearchDcoumets_Does_Not_Throw_On_Empty_Search_Document() + { + // Arrange + var documents = new List { new SearchDocument() }; + + // Act, Assert + this.internalSearchController.AddSearchDocuments(documents); + } + + [Test] + public void SearchController_Add_Throws_On_Zero_SearchTypeId() + { + // Arrange + + // Act, Assert + Assert.Throws( + () => this.internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString() })); + } + + [Test] + public void SearchController_Add_Throws_On_Negative_SearchTypeId() + { + // Arrange + + // Act, Assert + Assert.Throws( + () => + this.internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = -1 })); + } + + [Test] + public void SearchController_Add_Throws_On_DateTimeMin_ModifiedTimeUtc() + { + // Arrange + + // Act, Assert + Assert.Throws( + () => this.internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = 1 })); + } + + [Test] + public void SearchController_Add_Then_Delete_ModuleDefinition_WorksAsExpected() + { + // Arrange + const int totalDocs = 10; + var now = DateTime.UtcNow; + + // Act + for (var i = 1; i <= totalDocs; i++) + { + var doc = new SearchDocument + { + ModuleDefId = i, + ModuleId = 100, + SearchTypeId = ModuleSearchTypeId, + PortalId = PortalId0, + UniqueKey = Guid.NewGuid().ToString(), + ModifiedTimeUtc = now, + }; + + this.internalSearchController.AddSearchDocument(doc); + } + + // Assert + var stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); + + // Act - delete last item + var searchDoc = new SearchDocument { ModuleDefId = totalDocs }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); + Assert.AreEqual(1, stats.TotalDeletedDocuments); + + // Act - delete first item + searchDoc = new SearchDocument { ModuleDefId = 1 }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); + Assert.AreEqual(2, stats.TotalDeletedDocuments); + } + + [Test] + public void SearchController_Add_Then_Delete_Module_WorksAsExpected() + { + // Arrange + const int totalDocs = 10; + var now = DateTime.UtcNow; + + // Act + for (var i = 1; i <= totalDocs; i++) + { + var doc = new SearchDocument + { + ModuleId = i, + ModuleDefId = 10, + PortalId = PortalId0, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = ModuleSearchTypeId, + ModifiedTimeUtc = now, + }; + + this.internalSearchController.AddSearchDocument(doc); + } + + // Assert + var stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); + + // Act - delete last item + var searchDoc = new SearchDocument { ModuleId = totalDocs }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); + Assert.AreEqual(1, stats.TotalDeletedDocuments); + + // Act - delete first item + searchDoc = new SearchDocument { ModuleId = 1 }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); + Assert.AreEqual(2, stats.TotalDeletedDocuments); + } + + [Test] + public void SearchController_Add_Then_Delete_Portals_WorksAsExpected() + { + // Arrange + const int totalDocs = 10; // must be even + var now = DateTime.UtcNow; + + // Act + for (var i = 1; i <= totalDocs; i++) + { + var doc = new SearchDocument + { + PortalId = i <= (totalDocs / 2) ? PortalId0 : PortalId1, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = ModuleSearchTypeId, + ModifiedTimeUtc = now, + ModuleId = 100, + ModuleDefId = 10, + }; + + this.internalSearchController.AddSearchDocument(doc); + } + + // Assert + var stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); + + // Act - delete all portal 1 items + var searchDoc = new SearchDocument { PortalId = PortalId1 }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert - delete all portal 1 + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs / 2, stats.TotalActiveDocuments); + Assert.AreEqual(totalDocs / 2, stats.TotalDeletedDocuments); + } + + [Test] + public void SearchController_Add_Then_Delete_Roles_WorksAsExpected() + { + // Arrange + const int totalDocs = 10; + var now = DateTime.UtcNow; + + // Act + for (var i = 1; i <= totalDocs; i++) + { + var doc = new SearchDocument + { + RoleId = i, + PortalId = PortalId0, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = ModuleSearchTypeId, + ModifiedTimeUtc = now, + ModuleId = 100, + ModuleDefId = 10, + }; + + this.internalSearchController.AddSearchDocument(doc); + } + + // Assert + var stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); + + // Act - delete last item + var searchDoc = new SearchDocument { RoleId = totalDocs }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); + Assert.AreEqual(1, stats.TotalDeletedDocuments); + + // Act - delete first item + searchDoc = new SearchDocument { RoleId = 1 }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); + Assert.AreEqual(2, stats.TotalDeletedDocuments); + } + + [Test] + public void SearchController_Add_Then_Delete_Tabs_WorksAsExpected() + { + // Arrange + const int totalDocs = 10; + var now = DateTime.UtcNow; + + // Act + for (var i = 1; i <= totalDocs; i++) + { + var doc = new SearchDocument + { + TabId = i, + PortalId = PortalId0, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = TabSearchTypeId, + ModifiedTimeUtc = now, + }; + + this.internalSearchController.AddSearchDocument(doc); + } + + // Assert + var stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); + + // Act - delete last item + var searchDoc = new SearchDocument { TabId = totalDocs }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); + Assert.AreEqual(1, stats.TotalDeletedDocuments); + + // Act - delete first item + searchDoc = new SearchDocument { TabId = 1 }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); + Assert.AreEqual(2, stats.TotalDeletedDocuments); + } + + [Test] + public void SearchController_Add_Then_Delete_Users_WorksAsExpected() + { + // Arrange + const int totalDocs = 10; + var now = DateTime.UtcNow; + + // Act + for (var i = 1; i <= totalDocs; i++) + { + var doc = new SearchDocument + { + AuthorUserId = i, + PortalId = PortalId0, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = ModuleSearchTypeId, + ModifiedTimeUtc = now, + ModuleId = 100, + ModuleDefId = 10, + }; + + this.internalSearchController.AddSearchDocument(doc); + } + + // Assert + var stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); + + // Act - delete last item + var searchDoc = new SearchDocument { AuthorUserId = totalDocs }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); + Assert.AreEqual(1, stats.TotalDeletedDocuments); + + // Act - delete first item + searchDoc = new SearchDocument { AuthorUserId = 1 }; + this.internalSearchController.DeleteSearchDocument(searchDoc); + + // Assert + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); + Assert.AreEqual(2, stats.TotalDeletedDocuments); + } + + private void CreateNewLuceneControllerInstance() + { + this.DeleteIndexFolder(); + InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); + this.internalSearchController = InternalSearchController.Instance; + + if (this.luceneController != null) + { + LuceneController.ClearInstance(); + this.luceneController.Dispose(); + } + + this.luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this.luceneController); + } + + private void SetupHostController() + { + this.mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); + this.mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this.readerStaleTimeSpan); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())) + .Returns(Constants.DefaultSearchDescriptionBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); + this.mockHostController.As(); + } + + private void SetupLocaleController() + { + this.mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); + this.mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this.mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this.mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this.mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + + this.mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this.mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this.mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this.mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this.mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + } + + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this.mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + DataTableReader searchTypes = null; + this.mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) + .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) + .Returns(() => searchTypes); + + this.mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + } + + private IDataReader GetPortalsCallBack(string culture) + { + return this.GetPortalCallBack(PortalId0, CultureEnUs); + } + + private IDataReader GetPortalCallBack(int portalId, string culture) + { + var table = new DataTable("Portal"); + + var cols = new[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", + "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", + "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", + "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", + "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + const int homePage = 1; + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, + "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, + "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", + null, homePage.ToString("D"), null, null, "57", "56", "-1", "-1", "7", null, null, "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); + + return table.CreateDataReader(); + } + + private void SetupSearchHelper() + { + this.mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); + this.mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(this.GetSynonymsCallBack); + this.mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())) + .Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); + this.mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); + this.mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); + this.mockSearchHelper.Setup(c => c.GetSynonymsGroups(It.IsAny(), It.IsAny())).Returns(this.GetSynonymsGroupsCallBack); + this.mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( + new SearchStopWords + { + PortalId = 0, + CultureCode = CultureEsEs, + StopWords = "los,de,el", + }); + this.mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(new SearchHelperImpl().RephraseSearchText); + this.mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); + SearchHelper.SetTestableInstance(this.mockSearchHelper.Object); + } + + private IList GetSynonymsGroupsCallBack() + { + var groups = new List + { + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 1, SynonymsTags = string.Join(",", TermDNN, TermDotNetNuke) }, + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 2, SynonymsTags = string.Join(",", TermLaptop, TermNotebook) }, + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 3, SynonymsTags = string.Join(",", TermJump, TermLeap, TermHop) }, + }; + + return groups; + } + + private SearchType GetSearchTypeByNameCallback(string searchTypeName) + { + var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; + switch (searchTypeName) + { + case ModuleSearchTypeName: + searchType.SearchTypeId = ModuleSearchTypeId; + break; + case TabSearchTypeName: + searchType.SearchTypeId = TabSearchTypeId; + break; + case OtherSearchTypeName: + searchType.SearchTypeId = OtherSearchTypeId; + break; + case DocumentSearchTypeName: + searchType.SearchTypeId = DocumentSearchTypeId; + break; + case UrlSearchTypeName: + searchType.SearchTypeId = UrlSearchTypeId; + break; + } + + return searchType; + } + + private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) + { + var synonyms = new List(); if (term == "fox") { synonyms.Add("wolf"); } - return synonyms; - } - - private UserInfo GetUserByIdCallback(int portalId, int userId) - { - return new UserInfo { UserID = userId, DisplayName = "User" + userId, PortalID = portalId }; - } - - private DataTable GetAllSearchTypes() - { - var dtSearchTypes = new DataTable("SearchTypes"); - var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); - dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); - dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); - dtSearchTypes.PrimaryKey = new[] { pkId }; - - // Create default Crawler - dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(DocumentSearchTypeId, DocumentSearchTypeName, NoPermissionFakeResultControllerClass); - dtSearchTypes.Rows.Add(UrlSearchTypeId, UrlSearchTypeName, FakeResultControllerClass); - - return dtSearchTypes; - } - - private IEnumerable GetSearchTypes() - { - var searchTypes = new List - { - new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType - { - SearchTypeId = DocumentSearchTypeId, - SearchTypeName = DocumentSearchTypeName, - SearchResultClass = NoPermissionFakeResultControllerClass, - }, - new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, - }; - - return searchTypes; - } - - private void DeleteIndexFolder() - { - try - { - if (Directory.Exists(SearchIndexFolder)) - { - Directory.Delete(SearchIndexFolder, true); - } - } - catch (Exception ex) - { - Console.WriteLine(ex); - } - } - - private SearchStatistics GetSearchStatistics() - { - this._internalSearchController.Commit(); - Thread.Sleep((int)(this._readerStaleTimeSpan * 1000)); // time to flush data to Lucene - return this._internalSearchController.GetSearchStatistics(); - } - -#if false // the rules have changed and these are invalid tests now - [Test] - public void SearchController_Delete_Throws_On_Null_Or_Empty_UniqueuKey() - { - //Arrange - - //Act, Assert - var searchDoc = new SearchDocument() { UniqueKey = null, PortalId = 0, SearchTypeId = 1 }; - Assert.Throws(() => _internalSearchController.DeleteSearchDocument(searchDoc)); - } - - [Test] - public void SearchController_Delete_Throws_On_Zero_SearchTypeId() - { - //Arrange - - //Act, Assert - var searchDoc = new SearchDocument() { UniqueKey = "key", PortalId = 0, SearchTypeId = 0 }; - Assert.Throws(() => _internalSearchController.DeleteSearchDocument(searchDoc)); - } - - [Test] - public void SearchController_Delete_Throws_On_Negative_SearchTypeId() - { - //Arrange - - //Act, Assert - var searchDoc = new SearchDocument() { UniqueKey = "key", PortalId = 0, SearchTypeId = -1 }; - Assert.Throws(() => _internalSearchController.DeleteSearchDocument(searchDoc)); - } -#endif - - } -} + return synonyms; + } + + private UserInfo GetUserByIdCallback(int portalId, int userId) + { + return new UserInfo { UserID = userId, DisplayName = "User" + userId, PortalID = portalId }; + } + + private DataTable GetAllSearchTypes() + { + var dtSearchTypes = new DataTable("SearchTypes"); + var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); + dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); + dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); + dtSearchTypes.PrimaryKey = new[] { pkId }; + + // Create default Crawler + dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(DocumentSearchTypeId, DocumentSearchTypeName, NoPermissionFakeResultControllerClass); + dtSearchTypes.Rows.Add(UrlSearchTypeId, UrlSearchTypeName, FakeResultControllerClass); + + return dtSearchTypes; + } + + private IEnumerable GetSearchTypes() + { + var searchTypes = new List + { + new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType + { + SearchTypeId = DocumentSearchTypeId, + SearchTypeName = DocumentSearchTypeName, + SearchResultClass = NoPermissionFakeResultControllerClass, + }, + new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, + }; + + return searchTypes; + } + + private void DeleteIndexFolder() + { + try + { + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + } + + private SearchStatistics GetSearchStatistics() + { + this.internalSearchController.Commit(); + Thread.Sleep((int)(this.readerStaleTimeSpan * 1000)); // time to flush data to Lucene + return this.internalSearchController.GetSearchStatistics(); + } + +#if false // the rules have changed and these are invalid tests now + [Test] + public void SearchController_Delete_Throws_On_Null_Or_Empty_UniqueuKey() + { + //Arrange + + //Act, Assert + var searchDoc = new SearchDocument() { UniqueKey = null, PortalId = 0, SearchTypeId = 1 }; + Assert.Throws(() => _internalSearchController.DeleteSearchDocument(searchDoc)); + } + + [Test] + public void SearchController_Delete_Throws_On_Zero_SearchTypeId() + { + //Arrange + + //Act, Assert + var searchDoc = new SearchDocument() { UniqueKey = "key", PortalId = 0, SearchTypeId = 0 }; + Assert.Throws(() => _internalSearchController.DeleteSearchDocument(searchDoc)); + } + + [Test] + public void SearchController_Delete_Throws_On_Negative_SearchTypeId() + { + //Arrange + + //Act, Assert + var searchDoc = new SearchDocument() { UniqueKey = "key", PortalId = 0, SearchTypeId = -1 }; + Assert.Throws(() => _internalSearchController.DeleteSearchDocument(searchDoc)); + } +#endif + + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs index 58311a9a1c2..2a0c20442da 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs @@ -9,6 +9,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Search using System.IO; using System.Linq; using System.Threading; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; @@ -19,14 +20,17 @@ namespace DotNetNuke.Tests.Core.Controllers.Search using DotNetNuke.Services.Search.Entities; using DotNetNuke.Services.Search.Internals; using DotNetNuke.Tests.Utilities.Mocks; + using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.QueryParsers; using Lucene.Net.Search; + using Microsoft.Extensions.DependencyInjection; + using Moq; - using NUnit.Framework; + using NUnit.Framework; using Directory = System.IO.Directory; /// @@ -54,41 +58,36 @@ public class LuceneControllerTests // Arrange private const int TotalTestDocs2Create = 5; private const string ContentFieldName = "content"; - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; + private readonly double readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - private Mock _mockHostController; - private LuceneControllerImpl _luceneController; - private Mock _cachingProvider; - private Mock _mockSearchHelper; - private Mock _mockSearchQuery; + private Mock mockHostController; + private LuceneControllerImpl luceneController; + private Mock cachingProvider; + private Mock mockSearchHelper; + private Mock mockSearchQuery; [SetUp] public void SetUp() { ComponentFactory.Container = new SimpleContainer(); - this._cachingProvider = MockComponentProvider.CreateDataCacheProvider(); + this.cachingProvider = MockComponentProvider.CreateDataCacheProvider(); + + this.MockHostController(); + + this.mockSearchHelper = new Mock(); + this.mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.GetSynonymsCallBack); + this.mockSearchHelper.Setup(c => c.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); + this.mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); + this.mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); + SearchHelper.SetTestableInstance(this.mockSearchHelper.Object); var serviceCollection = new ServiceCollection(); serviceCollection.AddTransient(container => Mock.Of()); serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); + serviceCollection.AddTransient(container => (IHostSettingsService)this.mockHostController.Object); Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - this._mockHostController = new Mock(); - this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); - this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); - HostController.RegisterInstance(this._mockHostController.Object); - - this._mockSearchHelper = new Mock(); - this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.GetSynonymsCallBack); - this._mockSearchHelper.Setup(c => c.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); - this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); - this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); - SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); - - this._mockSearchQuery = new Mock(); + this.mockSearchQuery = new Mock(); this.DeleteIndexFolder(); this.CreateNewLuceneControllerInstance(); @@ -97,17 +96,36 @@ public void SetUp() [TearDown] public void TearDown() { - this._luceneController.Dispose(); + LuceneController.ClearInstance(); + this.luceneController.Dispose(); this.DeleteIndexFolder(); SearchHelper.ClearInstance(); Globals.DependencyProvider = null; + + this.mockHostController = null; + this.luceneController = null; + this.cachingProvider = null; + this.mockSearchHelper = null; + this.mockSearchQuery = null; + } + + private void MockHostController() + { + this.mockHostController = new Mock(); + + this.mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); + this.mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this.readerStaleTimeSpan); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); + this.mockHostController.As(); } [Test] public void LuceneController_SearchFolderIsAsExpected() { var inf1 = new DirectoryInfo(SearchIndexFolder); - var inf2 = new DirectoryInfo(this._luceneController.IndexFolder); + var inf2 = new DirectoryInfo(this.luceneController.IndexFolder); Assert.AreEqual(inf1.FullName, inf2.FullName); } @@ -117,7 +135,7 @@ public void LuceneController_Add_Throws_On_Null_Document() // Arrange // Act, Assert - Assert.Throws(() => this._luceneController.Add(null)); + Assert.Throws(() => this.luceneController.Add(null)); } public void LuceneController_Add_Throws_On_Null_Query() @@ -125,7 +143,7 @@ public void LuceneController_Add_Throws_On_Null_Query() // Arrange // Act, Assert - Assert.Throws(() => this._luceneController.Delete(null)); + Assert.Throws(() => this.luceneController.Delete(null)); } [Test] @@ -134,8 +152,8 @@ public void LuceneController_Add_Empty_FiledsCollection_DoesNot_Create_Index() // Arrange // Act - this._luceneController.Add(new Document()); - this._luceneController.Commit(); + this.luceneController.Add(new Document()); + this.luceneController.Commit(); var numFiles = 0; this.DeleteIndexFolder(); @@ -155,10 +173,10 @@ public void LuceneController_GetsHighlightedDesc() var doc = new Document(); doc.Add(field); - this._luceneController.Add(doc); - this._luceneController.Commit(); + this.luceneController.Add(doc); + this.luceneController.Commit(); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); // Assert Assert.AreEqual(1, hits.Results.Count()); @@ -180,10 +198,10 @@ public void LuceneController_HighlightedDescHtmlEncodesOutput() var doc = new Document(); doc.Add(field); - this._luceneController.Add(doc); - this._luceneController.Commit(); + this.luceneController.Add(doc); + this.luceneController.Commit(); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); // Assert Assert.AreEqual(1, hits.Results.Count()); @@ -201,11 +219,11 @@ public void LuceneController_FindsResultsUsingNearRealtimeSearchWithoutCommit() var field = new Field(fieldName, fieldValue, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); var doc = new Document(); doc.Add(field); - this._luceneController.Add(doc); + this.luceneController.Add(doc); // DONOT commit here to enable testing near-realtime of search writer // _luceneController.Commit(); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); // Assert Assert.AreEqual(1, hits.Results.Count()); @@ -217,7 +235,7 @@ public void LuceneController_Search_Returns_Correct_Total_Hits() // Arrange this.AddStandardDocs(); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")) })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")) })); // Assert Assert.AreEqual(4, hits.TotalHits); @@ -230,7 +248,7 @@ public void LuceneController_Search_Request_For_1_Result_Returns_1_Record_But_Mo // Arrange this.AddStandardDocs(); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 1 })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 1 })); // Assert Assert.AreEqual(4, hits.TotalHits); @@ -243,7 +261,7 @@ public void LuceneController_Search_Request_For_4_Records_Returns_4_Records_With // Arrange this.AddStandardDocs(); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 4 })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 4 })); // Assert Assert.AreEqual(4, hits.TotalHits); @@ -256,7 +274,7 @@ public void LuceneController_Search_Request_For_4_Records_Returns_4_Records_With // Arrange this.AddStandardDocs(); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 4 })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 4 })); // Assert Assert.AreEqual(4, hits.TotalHits); @@ -269,7 +287,7 @@ public void LuceneController_Search_Request_For_NonExisting_PageNumbers_Returns_ // Arrange this.AddStandardDocs(); - var hits = this._luceneController.Search(this.CreateSearchContext( + var hits = this.luceneController.Search(this.CreateSearchContext( new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), @@ -295,7 +313,7 @@ public void LuceneController_Search_Request_For_PagIndex2_PageSize1_Returns_2nd_ PageSize = 1, }; - var hits = this._luceneController.Search(this.CreateSearchContext(query)); + var hits = this.luceneController.Search(this.CreateSearchContext(query)); // Assert Assert.AreEqual(3, hits.TotalHits); @@ -317,27 +335,27 @@ public void LuceneController_NumericRangeCheck() // Add first numeric field var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - this._luceneController.Add(doc1); + this.luceneController.Add(doc1); // Add second numeric field var doc2 = new Document(); doc2.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(2)); - this._luceneController.Add(doc2); + this.luceneController.Add(doc2); // Add third numeric field var doc3 = new Document(); doc3.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(3)); - this._luceneController.Add(doc3); + this.luceneController.Add(doc3); // Add fourth numeric field var doc4 = new Document(); doc4.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(4)); - this._luceneController.Add(doc4); + this.luceneController.Add(doc4); - this._luceneController.Commit(); + this.luceneController.Commit(); var query = NumericRangeQuery.NewIntRange(fieldName, 2, 3, true, true); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); Assert.AreEqual(2, hits.Results.Count()); } @@ -353,48 +371,48 @@ public void LuceneController_DateRangeCheck() { var doc = new Document(); doc.Add(new NumericField(fieldName, Field.Store.YES, true).SetLongValue(long.Parse(date.ToString(Constants.DateTimeFormat)))); - this._luceneController.Add(doc); + this.luceneController.Add(doc); } - this._luceneController.Commit(); + this.luceneController.Commit(); var futureTime = DateTime.Now.AddMinutes(1).ToString(Constants.DateTimeFormat); var query = NumericRangeQuery.NewLongRange(fieldName, long.Parse(futureTime), long.Parse(futureTime), true, true); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); Assert.AreEqual(0, hits.Results.Count()); query = NumericRangeQuery.NewLongRange(fieldName, long.Parse(DateTime.Now.AddDays(-1).ToString(Constants.DateTimeFormat)), long.Parse(DateTime.Now.ToString(Constants.DateTimeFormat)), true, true); - hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); + hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); Assert.AreEqual(1, hits.Results.Count()); query = NumericRangeQuery.NewLongRange(fieldName, long.Parse(DateTime.Now.AddDays(-368).ToString(Constants.DateTimeFormat)), long.Parse(DateTime.Now.ToString(Constants.DateTimeFormat)), true, true); - hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); + hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); Assert.AreEqual(2, hits.Results.Count()); } [Test] public void LuceneController_Search_Throws_On_Null_LuceneQuery() { - Assert.Throws(() => this._luceneController.Search(this.CreateSearchContext(null))); + Assert.Throws(() => this.luceneController.Search(this.CreateSearchContext(null))); } [Test] public void LuceneController_Search_Throws_On_Null_Query() { - Assert.Throws(() => this._luceneController.Search(this.CreateSearchContext(new LuceneQuery()))); + Assert.Throws(() => this.luceneController.Search(this.CreateSearchContext(new LuceneQuery()))); } [Test] public void LuceneController_Search_Throws_On_Zero_PageSize() { - Assert.Throws(() => this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new BooleanQuery(), PageSize = 0 }))); + Assert.Throws(() => this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new BooleanQuery(), PageSize = 0 }))); } [Test] public void LuceneController_Search_Throws_On_Zero_PageIndex() { - Assert.Throws(() => this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new BooleanQuery(), PageIndex = 0 }))); + Assert.Throws(() => this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new BooleanQuery(), PageIndex = 0 }))); } [Test] @@ -403,7 +421,7 @@ public void LuceneController_Search_Throws_On_Zero_PageIndex() [TestCase(ValidCustomAnalyzer)] public void LuceneController_Search_With_Chinese_Chars_And_Custom_Analyzer(string customAlalyzer = "") { - this._mockHostController.Setup(c => c.GetString(Constants.SearchCustomAnalyzer, It.IsAny())).Returns(customAlalyzer); + this.mockHostController.Setup(controller => controller.GetString(Constants.SearchCustomAnalyzer, It.IsAny())).Returns(customAlalyzer); // Arrange const string fieldName = "content"; @@ -414,16 +432,16 @@ public void LuceneController_Search_With_Chinese_Chars_And_Custom_Analyzer(strin var doc = new Document(); doc.Add(field); - this._luceneController.Add(doc); - this._luceneController.Commit(); + this.luceneController.Add(doc); + this.luceneController.Commit(); - var analyzer = this._luceneController.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); + var analyzer = this.luceneController.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); var keywordQuery = new BooleanQuery(); var parserContent = new QueryParser(Constants.LuceneVersion, fieldName, analyzer); var parsedQueryContent = parserContent.Parse(SearchKeyword_Chinese); keywordQuery.Add(parsedQueryContent, Occur.SHOULD); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = keywordQuery })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = keywordQuery })); // Assert if (customAlalyzer == ValidCustomAnalyzer) @@ -443,7 +461,7 @@ public void LuceneController_Search_With_Chinese_Chars_And_Custom_Analyzer(strin [TestCase(ValidCustomAnalyzer)] public void LuceneController_Search_With_English_Chars_And_Custom_Analyzer(string customAlalyzer = "") { - this._mockHostController.Setup(c => c.GetString(Constants.SearchCustomAnalyzer, It.IsAny())).Returns(customAlalyzer); + this.mockHostController.Setup(c => c.GetString(Constants.SearchCustomAnalyzer, It.IsAny())).Returns(customAlalyzer); // Arrange const string fieldName = "content"; @@ -454,16 +472,16 @@ public void LuceneController_Search_With_English_Chars_And_Custom_Analyzer(strin var doc = new Document(); doc.Add(field); - this._luceneController.Add(doc); - this._luceneController.Commit(); + this.luceneController.Add(doc); + this.luceneController.Commit(); - var analyzer = this._luceneController.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); + var analyzer = this.luceneController.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); var keywordQuery = new BooleanQuery(); var parserContent = new QueryParser(Constants.LuceneVersion, fieldName, analyzer); var parsedQueryContent = parserContent.Parse(SearchKeyword_Line1); keywordQuery.Add(parsedQueryContent, Occur.SHOULD); - var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = keywordQuery })); + var hits = this.luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = keywordQuery })); // Assert Assert.AreEqual(1, hits.Results.Count()); @@ -485,7 +503,7 @@ public void LuceneController_Search_Single_FuzzyQuery() // Act var luceneQuery = new LuceneQuery { Query = new FuzzyQuery(new Term(Constants.ContentTag, keyword)) }; - var previews = this._luceneController.Search(this.CreateSearchContext(luceneQuery)); + var previews = this.luceneController.Search(this.CreateSearchContext(luceneQuery)); // Assert Assert.AreEqual(2, previews.Results.Count()); @@ -519,7 +537,7 @@ public void LuceneController_Search_Double_FuzzyQuery() } var luceneQuery = new LuceneQuery { Query = finalQuery }; - var previews = this._luceneController.Search(this.CreateSearchContext(luceneQuery)); + var previews = this.luceneController.Search(this.CreateSearchContext(luceneQuery)); // Assert Assert.AreEqual(3, previews.Results.Count()); @@ -528,7 +546,7 @@ public void LuceneController_Search_Double_FuzzyQuery() [Test] public void LuceneController_Throws_SearchIndexEmptyException_WhenNoDataInSearch() { - Assert.Throws(() => { var r = this._luceneController.GetSearcher(); }); + Assert.Throws(() => { var r = this.luceneController.GetSearcher(); }); } [Test] @@ -542,13 +560,13 @@ public void LuceneController_ReaderNotChangedBeforeTimeSpanElapsed() // Add first numeric field var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - this._luceneController.Add(doc1); - this._luceneController.Commit(); + this.luceneController.Add(doc1); + this.luceneController.Commit(); - var reader = this._luceneController.GetSearcher(); - Thread.Sleep(TimeSpan.FromSeconds(this._readerStaleTimeSpan / 2)); + var reader = this.luceneController.GetSearcher(); + Thread.Sleep(TimeSpan.FromSeconds(this.readerStaleTimeSpan / 2)); - Assert.AreSame(reader, this._luceneController.GetSearcher()); + Assert.AreSame(reader, this.luceneController.GetSearcher()); } [Test] @@ -562,13 +580,13 @@ public void LuceneController_ReaderNotChangedIfNoIndexUpdated() // Add first numeric field var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - this._luceneController.Add(doc1); - this._luceneController.Commit(); + this.luceneController.Add(doc1); + this.luceneController.Commit(); - var reader = this._luceneController.GetSearcher(); - Thread.Sleep(TimeSpan.FromSeconds(this._readerStaleTimeSpan * 1.1)); + var reader = this.luceneController.GetSearcher(); + Thread.Sleep(TimeSpan.FromSeconds(this.readerStaleTimeSpan * 1.1)); - Assert.AreSame(reader, this._luceneController.GetSearcher()); + Assert.AreSame(reader, this.luceneController.GetSearcher()); } [Test] @@ -582,20 +600,20 @@ public void LuceneController_ReaderIsChangedWhenIndexIsUpdatedAndTimeIsElapsed() // Add first numeric field var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - this._luceneController.Add(doc1); - this._luceneController.Commit(); + this.luceneController.Add(doc1); + this.luceneController.Commit(); - var reader = this._luceneController.GetSearcher(); - Thread.Sleep(TimeSpan.FromSeconds(this._readerStaleTimeSpan * 1.1)); + var reader = this.luceneController.GetSearcher(); + Thread.Sleep(TimeSpan.FromSeconds(this.readerStaleTimeSpan * 1.1)); // Add second numeric field var doc2 = new Document(); doc2.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(2)); - this._luceneController.Add(doc2); + this.luceneController.Add(doc2); // var lastAcccess = Directory.GetLastWriteTime(_luceneController.IndexFolder); // Directory.SetLastWriteTime(_luceneController.IndexFolder, lastAcccess + TimeSpan.FromSeconds(1)); - Assert.AreNotSame(reader, this._luceneController.GetSearcher()); + Assert.AreNotSame(reader, this.luceneController.GetSearcher()); } [Test] @@ -620,7 +638,7 @@ public void LuceneController_LockFileWhenExistsDoesNotCauseProblemForFirstIContr // Assert Assert.True(File.Exists(lockFile)); - Assert.DoesNotThrow(() => this._luceneController.Add(doc1)); + Assert.DoesNotThrow(() => this.luceneController.Add(doc1)); } [Test] @@ -633,7 +651,7 @@ public void LuceneController_LockFileCanBeObtainedByOnlySingleController() // Act var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - this._luceneController.Add(doc1); + this.luceneController.Add(doc1); // create another controller then try to access the already locked index by the first one var secondController = new LuceneControllerImpl(); @@ -648,8 +666,8 @@ public void LuceneController_DocumentMaxAndCountAreCorrect() { this.AddTestDocs(); - Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); - Assert.AreEqual(TotalTestDocs2Create, this._luceneController.SearchbleDocsCount()); + Assert.AreEqual(TotalTestDocs2Create, this.luceneController.MaxDocsCount()); + Assert.AreEqual(TotalTestDocs2Create, this.luceneController.SearchbleDocsCount()); } [Test] @@ -659,9 +677,9 @@ public void LuceneController_TestDeleteBeforeOptimize() this.AddTestDocs(); var delCount = this.DeleteTestDocs(); - Assert.IsTrue(this._luceneController.HasDeletions()); - Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); - Assert.AreEqual(TotalTestDocs2Create - delCount, this._luceneController.SearchbleDocsCount()); + Assert.IsTrue(this.luceneController.HasDeletions()); + Assert.AreEqual(TotalTestDocs2Create, this.luceneController.MaxDocsCount()); + Assert.AreEqual(TotalTestDocs2Create - delCount, this.luceneController.SearchbleDocsCount()); } [Test] @@ -671,10 +689,10 @@ public void LuceneController_TestDeleteAfterOptimize() this.AddTestDocs(); var delCount = this.DeleteTestDocs(); - this._luceneController.OptimizeSearchIndex(true); + this.luceneController.OptimizeSearchIndex(true); - Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); - Assert.AreEqual(TotalTestDocs2Create - delCount, this._luceneController.SearchbleDocsCount()); + Assert.AreEqual(TotalTestDocs2Create, this.luceneController.MaxDocsCount()); + Assert.AreEqual(TotalTestDocs2Create - delCount, this.luceneController.SearchbleDocsCount()); } [Test] @@ -683,7 +701,7 @@ public void LuceneController_TestGetSearchStatistics() // Arrange var addedCount = this.AddTestDocs(); var delCount = this.DeleteTestDocs(); - var statistics = this._luceneController.GetSearchStatistics(); + var statistics = this.luceneController.GetSearchStatistics(); Assert.IsNotNull(statistics); Assert.AreEqual(statistics.TotalDeletedDocuments, delCount); @@ -698,19 +716,19 @@ public void SearchController_LuceneControllerReaderIsNotNullWhenWriterIsNull() this.CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion // Assert - Assert.IsNotNull(this._luceneController.GetSearcher()); + Assert.IsNotNull(this.luceneController.GetSearcher()); } private void CreateNewLuceneControllerInstance() { - if (this._luceneController != null) + if (this.luceneController != null) { LuceneController.ClearInstance(); - this._luceneController.Dispose(); + this.luceneController.Dispose(); } - this._luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(this._luceneController); + this.luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this.luceneController); } private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) @@ -759,10 +777,10 @@ private void AddLinesAsSearchDocs(IEnumerable lines) var field = new Field(Constants.ContentTag, line, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); var doc = new Document(); doc.Add(field); - this._luceneController.Add(doc); + this.luceneController.Add(doc); } - this._luceneController.Commit(); + this.luceneController.Commit(); } private int AddTestDocs() @@ -774,10 +792,10 @@ private int AddTestDocs() // format to "D#" because LengthFilter will not consider words of length < 3 or > 255 characters in length (defaults) doc.Add(new Field(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen), Field.Store.YES, Field.Index.ANALYZED)); - this._luceneController.Add(doc); + this.luceneController.Add(doc); } - this._luceneController.Commit(); + this.luceneController.Commit(); return TotalTestDocs2Create; } @@ -789,17 +807,17 @@ private int DeleteTestDocs() for (var i = 1; i < TotalTestDocs2Create; i += 2) { // format to "D#" because LengthFilter will not consider the defaults for these values - this._luceneController.Delete(new TermQuery(new Term(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen)))); + this.luceneController.Delete(new TermQuery(new Term(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen)))); delCount++; } - this._luceneController.Commit(); + this.luceneController.Commit(); return delCount; } private LuceneSearchContext CreateSearchContext(LuceneQuery luceneQuery) { - return new LuceneSearchContext { LuceneQuery = luceneQuery, SearchQuery = this._mockSearchQuery.Object }; + return new LuceneSearchContext { LuceneQuery = luceneQuery, SearchQuery = this.mockSearchQuery.Object }; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs index c8f6ce90b60..decd86551ad 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs @@ -2,2993 +2,2998 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Controllers.Search -{ - using System; - using System.Collections.Generic; - using System.Data; - using System.IO; - using System.Linq; +namespace DotNetNuke.Tests.Core.Controllers.Search +{ + using System; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Linq; using System.Threading; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.ComponentModel; - using DotNetNuke.Data; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Users; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.Localization; - using DotNetNuke.Services.Search.Controllers; - using DotNetNuke.Services.Search.Entities; - using DotNetNuke.Services.Search.Internals; - using DotNetNuke.Tests.Utilities.Mocks; - using Lucene.Net.Documents; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Search.Controllers; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Tests.Utilities.Mocks; + using Microsoft.Extensions.DependencyInjection; - using Moq; - using NUnit.Framework; - - using Constants = DotNetNuke.Services.Search.Internals.Constants; - - /// - /// Testing various aspects of SearchController. - /// - [TestFixture] - public class SearchControllerTests - { - private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; - private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; - private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; - private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; - private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; - private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; - private const int PortalId0 = 0; - private const int PortalId12 = 12; - private const int IdeasModuleDefId = 201; - private const int BlogsoduleDefId = 202; - private const int AnswersModuleDefId = 203; - private const int HtmlModuleDefId = 20; - private const int HtmlModuleId = 25; - private const int IdeasModuleId = 301; - private const int BlogsModuleId = 302; - private const int AnswersModuleId = 303; - private const int RoleId731 = 731; - private const int RoleId532 = 532; - private const int RoleId0 = 0; - private const string Tag0 = "tag0"; - private const string Tag0WithSpace = "tag0 hello"; - private const string Tag1 = "tag1"; - private const string Tag2 = "tag2"; - private const string Tag3 = "tag3"; - private const string Tag4 = "tag4"; - private const string TagTootsie = "tootsie"; - private const string TagLatest = "latest"; - private const string TagOldest = "oldest"; - private const string TagIt = "IT"; - private const string TagNeutral = "Neutral"; - private const string ModuleSearchTypeName = "module"; - private const string OtherSearchTypeName = "other"; - private const string TabSearchTypeName = "tab"; - private const string DocumentSearchTypeName = "document"; - private const string UrlSearchTypeName = "url"; - private const string ModuleResultControllerClass = "DotNetNuke.Services.Search.Crawlers.ModuleResultController, DotNetNuke"; - private const string FakeResultControllerClass = "DotNetNuke.Tests.Core.Controllers.Search.FakeResultController, DotNetNuke.Tests.Core"; - private const string NoPermissionFakeResultControllerClass = "DotNetNuke.Tests.Core.Controllers.Search.NoPermissionFakeResultController, DotNetNuke.Tests.Core"; - private const string CultureEnUs = "en-US"; - private const string CultureEnCa = "en-CA"; - private const string CultureItIt = "it-IT"; - private const string CultureEsEs = "es-ES"; - private const int LanguageIdEnUs = 1; - private const int LanguageIdEnFr = 2; - private const int LanguageIdItIt = 3; - private const int LanguageIdEsEs = 4; - private const int StandardAuthorId = 55; - private const int StandardRoleId = 66; - private const string StandardAuthorDisplayName = "Standard User"; - private const int StandardTabId = 99; - private const string StandardPermission = "!Translator (en-US);![4];[5];[6];Administrators;ContentEditorRole;"; - private const string StandardQueryString = "cid=1"; - private const string NumericKey1 = "numerickey1"; - private const string NumericKey2 = "numerickey2"; - private const int NumericValue1 = 77777; - private const int NumericValue2 = 55555; - private const int NumericValue50 = 50; - private const int NumericValue100 = 100; - private const int NumericValue200 = 200; - private const int NumericValue500 = 500; - private const int NumericValue1000 = 1000; - private const string KeyWord1Name = "keyword1"; - private const string KeyWord1Value = "value1"; - private const string KeyWord2Name = "keyword2"; - private const string KeyWord2Value = "value2"; - private const string KeyWord3Value = "value3"; - private const string KeyWord4Value = "value4"; - private const string KeyWord5Value = "value5"; - private const string Line1 = "The quick brown fox jumps over the lazy dog"; - private const string Line2 = "The quick gold fox jumped over the lazy black dog"; - private const string Line3 = "the quick fox jumps over the black dog - Italian"; - private const string Line4 = "the red fox jumped over the lazy dark gray dog"; - private const string Line5 = "the quick fox jumps over the white dog - los de el Espana"; - - private const int CustomBoost = 80; - - private const string SearchIndexFolder = @"App_Data\SearchTests"; - private const int DefaultSearchRetryTimes = 5; - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - private Mock _mockHostController; - private Mock _mockCachingProvider; - private Mock _mockDataProvider; - private Mock _mockLocaleController; - private Mock _mockSearchHelper; - private Mock _mockUserController; - - private SearchControllerImpl _searchController; - private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; - - public enum SearchTypeIds - { - ModuleSearchTypeId = 1, - TabSearchTypeId, - DocumentSearchTypeId, - UrlSearchTypeId, - OtherSearchTypeId, - UnknownSearchTypeId, - } - - [SetUp] - public void SetUp() - { - ComponentFactory.Container = new SimpleContainer(); - MockComponentProvider.ResetContainer(); - - var serviceCollection = new ServiceCollection(); - serviceCollection.AddTransient(container => Mock.Of()); - serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - this._mockDataProvider = MockComponentProvider.CreateDataProvider(); - this._mockLocaleController = MockComponentProvider.CreateLocaleController(); - this._mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - - this._mockUserController = new Mock(); - this._mockHostController = new Mock(); - this._mockSearchHelper = new Mock(); - - this.SetupDataProvider(); - this.SetupHostController(); - this.SetupSearchHelper(); - this.SetupLocaleController(); - - this._mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns((int portalId, int userId) => this.GetUserByIdCallback(portalId, userId)); - UserController.SetTestableInstance(this._mockUserController.Object); - - this.CreateNewLuceneControllerInstance(); - } - - [TearDown] - public void TearDown() - { - this._luceneController.Dispose(); - this.DeleteIndexFolder(); - InternalSearchController.ClearInstance(); - UserController.ClearInstance(); - SearchHelper.ClearInstance(); - LuceneController.ClearInstance(); - this._luceneController = null; - Globals.DependencyProvider = null; - } - - [Test] - public void SearchController_Search_Throws_On_Null_Query() - { - // Arrange - - // Act, Assert - Assert.Throws(() => this._searchController.SiteSearch(null)); - } - - [Test] - public void SearchController_Search_Throws_On_Empty_TypeId_Collection() - { - // Arrange - - // Act, Assert - Assert.Throws(() => this._searchController.SiteSearch(new SearchQuery { KeyWords = "word" })); - } - - [Test] - public void SearchController_AddSearchDcoumet_Regex_Does_Not_Sleep_On_Bad_Text_During_Alt_Text_Parsing() - { - // Arrange - var document = new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "< ExecuteWithTimeout( - () => - { - this._internalSearchController.AddSearchDocument(document); - return false; - }, TimeSpan.FromSeconds(1))); - } - - [Test] - public void SearchController_Added_Item_IsRetrieved() - { - // Arrange - var doc = new SearchDocument { UniqueKey = "key01", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - - // Act - this._internalSearchController.AddSearchDocument(doc); - - var result = this.SearchForKeyword("hello"); - - // Assert - Assert.AreEqual(1, result.Results.Count); - Assert.AreEqual(result.Results[0].UniqueKey, doc.UniqueKey); - Assert.AreEqual(result.Results[0].Title, doc.Title); - } - - [Test] - public void SearchController_EnsureIndexIsAppended_When_Index_Is_NotDeleted_InBetween() - { - // Arrange - string[] docs = - { - Line1, - Line2, - }; - - // Act - - // Add first document - var doc1 = new SearchDocument { Title = docs[0], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - this._internalSearchController.AddSearchDocument(doc1); - - // first luceneQuery - var query1 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; - var search1 = this._searchController.SiteSearch(query1); - - // Assert - Assert.AreEqual(1, search1.Results.Count); - - // Add second document - var doc2 = new SearchDocument { Title = docs[1], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - this._internalSearchController.AddSearchDocument(doc2); - this.CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion - - // second luceneQuery - var query2 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; - var search2 = this._searchController.SiteSearch(query2); - - // Assert - Assert.AreEqual(2, search2.Results.Count); - } - - [Test] - public void SearchController_Getsearch_TwoTermsSearch() - { - // Arrange - string[] docs = - { - Line1, - Line2, - Line3, - Line4, - Line5, - }; - - this.AddLinesAsSearchDocs(docs); - - // Act - var search = this.SearchForKeyword("fox jumps"); - - // Assert - Assert.AreEqual(docs.Length, search.Results.Count); - - // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); - // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); - } - - [Test] - public void SearchController_GetResult_TwoTermsSearch() - { - // Arrange - string[] docs = - { - Line1, - Line2, - Line3, - Line4, - Line5, - }; - - this.AddLinesAsSearchDocs(docs); - - // Act - var search = this.SearchForKeyword("fox jumps"); - - // Assert - Assert.AreEqual(docs.Length, search.Results.Count); - - // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); - // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); - } - - [Test] - public void SearchController_GetResult_PortalIdSearch() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, PortalIds = new List { PortalId0 } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - } - - [Test] - public void SearchController_GetResult_SearchTypeIdSearch() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - } - - [Test] - public void SearchController_SearchFindsAnalyzedVeryLongWords() - { - // Arrange - // const string fieldName = Constants.ContentTag; - const string veryLongWord = // 107 characters - "NowIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountryalsoIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountry"; - - var doc = new SearchDocument - { - Title = veryLongWord, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = ModuleSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - ModuleId = 1, - ModuleDefId = 1, - }; - this._internalSearchController.AddSearchDocument(doc); - - // Act - var query = new SearchQuery { KeyWords = veryLongWord, SearchTypeIds = new List { ModuleSearchTypeId } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual("" + veryLongWord + "", this.StipEllipses(search.Results[0].Snippet).Trim()); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsNoResultsWhenHavingNoPermission() - { - // Arrange - this.AddStandardSearchDocs(DocumentSearchTypeId); - - // Act - var result = this.SearchForKeyword("fox", DocumentSearchTypeId); - - // Assert - // by default AuthorUserId = 0 which have no permission, so this passes - Assert.AreEqual(0, result.Results.Count); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1A() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 1, - PageSize = 4, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(new[] { 6, 7, 8, 9 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1B() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 1, - PageSize = 6, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1C() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 1, - PageSize = 8, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1D() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; // user should have access to some documnets here - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 1, - PageSize = 100, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(4 * 3, result.TotalHits); - Assert.AreEqual(4 * 3, result.Results.Count); - Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1E() - { - // Arrange - const int maxDocs = 30; - const int stype = TabSearchTypeId; // user should have access to all documnets here - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 1, - PageSize = 10, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).Skip(1).ToArray(); - - // Assert - Assert.AreEqual(maxDocs, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(Enumerable.Range(1, 9).ToArray(), ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1F() - { - // Arrange - const int maxDocs = 100; - const int stype = TabSearchTypeId; // user should have access to all documnets here - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 10, - PageSize = 10, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(Enumerable.Range(90, 10).ToArray(), ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2A() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 2, - PageSize = 5, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(5, result.Results.Count); - Assert.AreEqual(new[] { 17, 18, 19, 26, 27 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2B() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 2, - PageSize = 6, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(6, result.Results.Count); - Assert.AreEqual(new[] { 18, 19, 26, 27, 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2C() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 2, - PageSize = 8, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(4, result.Results.Count); - Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3A() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var queryPg3 = new SearchQuery - { - PageIndex = 3, - PageSize = 4, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(queryPg3); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(queryPg3.PageSize, result.Results.Count); - Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3B() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var queryPg3 = new SearchQuery - { - PageIndex = 3, - PageSize = 5, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(queryPg3); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(2, result.Results.Count); - Assert.AreEqual(new[] { 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3C() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var queryPg3 = new SearchQuery - { - PageIndex = 3, - PageSize = 8, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(queryPg3); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(0, result.Results.Count); - Assert.AreEqual(new int[] { }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage5() - { - // Arrange - const int maxDocs = 100; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var queryPg3 = new SearchQuery - { - PageIndex = 5, - PageSize = 8, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(queryPg3); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - (10 * 6), result.TotalHits); - Assert.AreEqual(queryPg3.PageSize, result.Results.Count); - Assert.AreEqual(new int[] { 86, 87, 88, 89, 96, 97, 98, 99 }, ids); - } - - [Test] - public void SearchController_GetResult_Returns_Correct_SuppliedData_When_Optionals_Are_Supplied() - { - // Arrange - var modifiedDateTime = DateTime.UtcNow; - var numericKeys = new Dictionary() { { NumericKey1, NumericValue1 }, { NumericKey2, NumericValue2 } }; - var keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value }, { KeyWord2Name, KeyWord2Value } }; - var tags = new List { Tag1, Tag2 }; - var doc = new SearchDocument - { - Title = "Title", - UniqueKey = "key", - SearchTypeId = ModuleSearchTypeId, - ModifiedTimeUtc = modifiedDateTime, - PortalId = PortalId12, - TabId = StandardTabId, - ModuleDefId = HtmlModuleDefId, - ModuleId = HtmlModuleId, - Description = "Description", - Body = "Body", - AuthorUserId = StandardAuthorId, - RoleId = StandardRoleId, - Permissions = StandardPermission, - QueryString = StandardQueryString, - Tags = tags, - NumericKeys = numericKeys, - Keywords = keywords, - }; - this._internalSearchController.AddSearchDocument(doc); - - // run luceneQuery on common keyword between both the docs - var search = this.SearchForKeywordInModule("Title"); - - // Assert - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual(PortalId12, search.Results[0].PortalId); - Assert.AreEqual(StandardTabId, search.Results[0].TabId); - Assert.AreEqual(HtmlModuleDefId, search.Results[0].ModuleDefId); - Assert.AreEqual(HtmlModuleId, search.Results[0].ModuleId); - Assert.AreEqual(ModuleSearchTypeId, search.Results[0].SearchTypeId); - Assert.AreEqual("Description", search.Results[0].Description); - Assert.AreEqual("Body", search.Results[0].Body); - Assert.AreEqual(StandardAuthorId, search.Results[0].AuthorUserId); - Assert.AreEqual(StandardRoleId, search.Results[0].RoleId); - Assert.AreEqual(modifiedDateTime.ToString(Constants.DateTimeFormat), search.Results[0].ModifiedTimeUtc.ToString(Constants.DateTimeFormat)); - Assert.AreEqual(StandardPermission, search.Results[0].Permissions); - Assert.AreEqual(StandardQueryString, search.Results[0].QueryString); - Assert.AreEqual(StandardAuthorDisplayName, search.Results[0].AuthorName); - Assert.AreEqual(tags.Count, search.Results[0].Tags.Count()); - Assert.AreEqual(tags[0], search.Results[0].Tags.ElementAt(0)); - Assert.AreEqual(tags[1], search.Results[0].Tags.ElementAt(1)); - Assert.AreEqual(numericKeys.Count, search.Results[0].NumericKeys.Count); - Assert.AreEqual(numericKeys[NumericKey1], search.Results[0].NumericKeys[NumericKey1]); - Assert.AreEqual(numericKeys[NumericKey2], search.Results[0].NumericKeys[NumericKey2]); - Assert.AreEqual(keywords.Count, search.Results[0].Keywords.Count); - Assert.AreEqual(keywords[KeyWord1Name], search.Results[0].Keywords[KeyWord1Name]); - Assert.AreEqual(keywords[KeyWord2Name], search.Results[0].Keywords[KeyWord2Name]); - } - - [Test] - public void SearchController_GetResult_Returns_EmptyData_When_Optionals_Are_Not_Supplied() - { - // Arrange - var modifiedDateTime = DateTime.UtcNow; - var doc = new SearchDocument - { - PortalId = PortalId0, - Title = "Title", - UniqueKey = "key", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = modifiedDateTime, - }; - this._internalSearchController.AddSearchDocument(doc); - - var search = this.SearchForKeyword("Title"); - - // Assert - - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual(PortalId0, search.Results[0].PortalId); - Assert.AreEqual(0, search.Results[0].TabId); - Assert.AreEqual(0, search.Results[0].ModuleDefId); - Assert.AreEqual(0, search.Results[0].ModuleId); - Assert.AreEqual(OtherSearchTypeId, search.Results[0].SearchTypeId); - Assert.AreEqual(null, search.Results[0].Description); - Assert.AreEqual(null, search.Results[0].Body); - Assert.AreEqual(0, search.Results[0].AuthorUserId); - Assert.AreEqual(-1, search.Results[0].RoleId); - Assert.AreEqual(modifiedDateTime.ToString(Constants.DateTimeFormat), search.Results[0].ModifiedTimeUtc.ToString(Constants.DateTimeFormat)); - Assert.AreEqual(null, search.Results[0].Permissions); - Assert.AreEqual(null, search.Results[0].QueryString); - Assert.AreEqual(null, search.Results[0].AuthorName); - Assert.AreEqual(0, search.Results[0].Tags.Count()); - Assert.AreEqual(0, search.Results[0].NumericKeys.Count); - Assert.AreEqual(0, search.Results[0].Keywords.Count); - } - - [Test] - public void SearchController_GetsHighlightedDesc() - { - // Arrange - string[] docs = - { - Line1, - Line2, - Line3, - Line4, - Line5, - }; - this.AddLinesAsSearchDocs(docs); - - // Act - var search = this.SearchForKeyword("fox"); - - // Assert - Assert.AreEqual(docs.Length, search.Results.Count); - Assert.IsTrue( - new[] - { - "brown fox jumps over the lazy dog", - "quick fox jumps over the black dog - Italian", - "gold fox jumped over the lazy black dog", - "e red fox jumped over the lazy dark gray dog", - "quick fox jumps over the white dog - los de el Espana", - }.SequenceEqual(search.Results.Select(r => this.StipEllipses(r.Snippet))), - "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Snippet))); - } - - [Test] - public void SearchController_CorrectDocumentCultureIsUsedAtIndexing() - { - // Arrange - // assign a culture that is different than the current one - var isNonEnglishEnv = Thread.CurrentThread.CurrentCulture.Name != CultureEsEs; - string cultureCode, title, searchWord; - - // Act - if (isNonEnglishEnv) - { - cultureCode = CultureEsEs; - searchWord = "zorro"; - title = "los rápidos saltos de zorro sobre el perro negro"; - } - else - { - cultureCode = CultureEnUs; - searchWord = "fox"; - title = Line3; - } - - this._internalSearchController.AddSearchDocument( - new SearchDocument - { - Title = title, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - CultureCode = cultureCode, - }); - this._internalSearchController.Commit(); - - var searches = this.SearchForKeyword(searchWord); - - // Assert - Assert.AreEqual(1, searches.TotalHits); - Assert.AreEqual(cultureCode, searches.Results[0].CultureCode); - } - - [Test] - public void SearchController_GetResult_TimeRangeSearch_Ignores_When_Only_BeginDate_Specified() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, BeginModifiedTimeUtc = DateTime.Now }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - } - - [Test] - public void SearchController_GetResult_TimeRangeSearch_Resturns_Scoped_Results_When_BeginDate_Is_After_End_Date() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - BeginModifiedTimeUtc = DateTime.Now, - EndModifiedTimeUtc = DateTime.Now.AddSeconds(-1), - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - } - - [Test] - public void SearchController_GetResult_TimeRangeSearch_Resturns_Scoped_Results_When_Both_Dates_Specified() - { - // Arrange - var added = this.AddStandardSearchDocs(); - var stypeIds = new List { ModuleSearchTypeId }; - var utcNow = DateTime.UtcNow.AddDays(1); - const SortFields sfield = SortFields.LastModified; - - // Act and Assert - just a bit later - var query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddSeconds(1), EndModifiedTimeUtc = utcNow.AddDays(1) }; - var search = this._searchController.SiteSearch(query); - Assert.AreEqual(0, search.Results.Count); - - // Act and Assert - 10 day - query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-10), EndModifiedTimeUtc = utcNow.AddDays(1) }; - search = this._searchController.SiteSearch(query); - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual(Line5, search.Results[0].Title); - - // Act and Assert - 1 year or so - query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-368), EndModifiedTimeUtc = utcNow.AddDays(1) }; - search = this._searchController.SiteSearch(query); - Assert.AreEqual(2, search.Results.Count); - Assert.AreEqual(Line5, search.Results[0].Title); - Assert.AreEqual(Line4, search.Results[1].Title); - - // Act and Assert - 2 years or so - query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-800), EndModifiedTimeUtc = utcNow.AddDays(1) }; - search = this._searchController.SiteSearch(query); - Assert.AreEqual(3, search.Results.Count); - Assert.AreEqual(Line5, search.Results[0].Title); - Assert.AreEqual(Line4, search.Results[1].Title); - Assert.AreEqual(Line3, search.Results[2].Title); - - // Act and Assert - 3 years or so - query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-1200), EndModifiedTimeUtc = utcNow.AddDays(1) }; - search = this._searchController.SiteSearch(query); - Assert.AreEqual(4, search.Results.Count); - Assert.AreEqual(Line5, search.Results[0].Title); - Assert.AreEqual(Line4, search.Results[1].Title); - Assert.AreEqual(Line3, search.Results[2].Title); - Assert.AreEqual(Line2, search.Results[3].Title); - - // Act and Assert - 2 to 3 years or so - query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-1200), EndModifiedTimeUtc = utcNow.AddDays(-800) }; - search = this._searchController.SiteSearch(query); - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual(Line2, search.Results[0].Title); - } - - [Test] - public void SearchController_GetResult_TagSearch_Single_Tag_Returns_Single_Result() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0 } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - } - - [Test] - public void SearchController_GetResult_TagSearch_Single_Tag_With_Space_Returns_Single_Result() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0WithSpace } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - } - - [Test] - public void SearchController_GetResult_TagSearch_Lowercase_Search_Returns_PropercaseTag_Single_Result() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { TagNeutral.ToLowerInvariant() } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - } - - [Test] - public void SearchController_GetResult_TagSearch_Single_Tag_Returns_Two_Results() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag1 } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(2, search.Results.Count); - Assert.AreEqual(Tag0, search.Results[0].Tags.ElementAt(0)); - Assert.AreEqual(Tag1, search.Results[0].Tags.ElementAt(1)); - Assert.AreEqual(Tag1, search.Results[1].Tags.ElementAt(0)); - Assert.AreEqual(Tag2, search.Results[1].Tags.ElementAt(1)); - } - - [Test] - public void SearchController_GetResult_TagSearch_Two_Tags_Returns_Nothing() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0, Tag4 } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(0, search.Results.Count); - } - - [Test] - public void SearchController_GetResult_TagSearch_Two_Tags_Returns_Single_Results() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag1, Tag2 } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual(Tag1, search.Results[0].Tags.ElementAt(0)); - Assert.AreEqual(Tag2, search.Results[0].Tags.ElementAt(1)); - } - - [Test] - public void SearchController_GetResult_TagSearch_With_Vowel_Tags_Returns_Data() - { - // Arrange - const string keyword = "awesome"; - var doc1 = new SearchDocument { UniqueKey = "key01", Title = keyword, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { TagTootsie } }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { OtherSearchTypeId }, Tags = new List { TagTootsie } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SearchController_GetResult_Throws_When_CustomNumericField_Is_Specified_And_CustomSortField_Is_Not() - { - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.CustomNumericField, - }; - - this._searchController.SiteSearch(query); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SearchController_GetResult_Throws_When_CustomStringField_Is_Specified_And_CustomSortField_Is_Not() - { - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.CustomStringField, - }; - - this._searchController.SiteSearch(query); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SearchController_GetResult_Throws_When_NumericKey_Is_Specified_And_CustomSortField_Is_Not() - { - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.NumericKey, - }; - - this._searchController.SiteSearch(query); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void SearchController_GetResult_Throws_When_Keyword_Is_Specified_And_CustomSortField_Is_Not() - { - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Keyword, - }; - - this._searchController.SiteSearch(query); - } - - [Test] - public void SearchController_GetResult_Sorty_By_Date_Returns_Latest_Docs_First() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.LastModified, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - - Assert.AreEqual(Tag3, search.Results[1].Tags.ElementAt(0)); - Assert.AreEqual(Tag4, search.Results[1].Tags.ElementAt(1)); - Assert.AreEqual(TagLatest, search.Results[1].Tags.ElementAt(2)); - - Assert.AreEqual(Tag2, search.Results[0].Tags.ElementAt(0)); - Assert.AreEqual(Tag3, search.Results[0].Tags.ElementAt(1)); - Assert.AreEqual(TagIt.ToLowerInvariant(), search.Results[0].Tags.ElementAt(2)); - } - - [Test] - public void SearchController_GetResult_Sorty_By_Date_Ascending_Returns_Earliest_Docs_First() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.LastModified, - SortDirection = SortDirections.Ascending, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.Greater(search.Results[1].DisplayModifiedTime, search.Results[0].DisplayModifiedTime); - Assert.Greater(search.Results[2].DisplayModifiedTime, search.Results[1].DisplayModifiedTime); - Assert.Greater(search.Results[3].DisplayModifiedTime, search.Results[2].DisplayModifiedTime); - - Assert.AreEqual(Tag0, search.Results[0].Tags.ElementAt(0)); - Assert.AreEqual(Tag1, search.Results[0].Tags.ElementAt(1)); - Assert.AreEqual(TagOldest, search.Results[0].Tags.ElementAt(2)); - } - - [Test] - public void SearchController_GetResult_Sorty_By_NumericKeys_Ascending_Returns_Smaller_Numers_First() - { - var added = this.AddDocumentsWithNumericKeys(); - - // Act - var query = new SearchQuery - { - KeyWords = "Title", - SearchTypeIds = new List { OtherSearchTypeId }, - SortField = SortFields.NumericKey, - SortDirection = SortDirections.Ascending, - CustomSortField = NumericKey1, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.Greater(search.Results[1].NumericKeys[NumericKey1], search.Results[0].NumericKeys[NumericKey1]); - Assert.Greater(search.Results[2].NumericKeys[NumericKey1], search.Results[1].NumericKeys[NumericKey1]); - } - - [Test] - public void SearchController_GetResult_Sorty_By_NumericKeys_Descending_Returns_Bigger_Numbers_First() - { - var added = this.AddDocumentsWithNumericKeys(); - - // Act - var query = new SearchQuery - { - KeyWords = "Title", - SearchTypeIds = new List { OtherSearchTypeId }, - SortField = SortFields.NumericKey, - SortDirection = SortDirections.Descending, - CustomSortField = NumericKey1, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.Greater(search.Results[0].NumericKeys[NumericKey1], search.Results[1].NumericKeys[NumericKey1]); - Assert.Greater(search.Results[1].NumericKeys[NumericKey1], search.Results[2].NumericKeys[NumericKey1]); - } - - [Test] - public void SearchController_GetResult_Sorty_By_Title_Ascending_Returns_Alphabetic_Ascending() - { - var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; - - var added = this.AddDocuments(titles, "animal"); - - // Act - var query = new SearchQuery - { - KeyWords = "animal", - SearchTypeIds = new List { OtherSearchTypeId }, - SortField = SortFields.Title, - SortDirection = SortDirections.Ascending, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - - var count = 0; - foreach (var title in titles.OrderBy(s => s)) - { - Assert.AreEqual(title, search.Results[count++].Title); - } - } - - [Test] - public void SearchController_GetResult_Sorty_By_Title_Descending_Returns_Alphabetic_Descending() - { - var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; - - var added = this.AddDocuments(titles, "animal"); - - // Act - var query = new SearchQuery - { - KeyWords = "animal", - SearchTypeIds = new List { OtherSearchTypeId }, - SortField = SortFields.Title, - SortDirection = SortDirections.Descending, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - - var count = 0; - foreach (var title in titles.OrderByDescending(s => s)) - { - Assert.AreEqual(title, search.Results[count++].Title); - } - } - - [Test] - public void SearchController_GetResult_Sorty_By_Keyword_Ascending_Returns_Alphabetic_Ascending() - { - var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; - - var added = this.AddDocumentsWithKeywords(titles, "animal"); - - // Act - var query = new SearchQuery - { - KeyWords = "animal", - SearchTypeIds = new List { OtherSearchTypeId }, - SortField = SortFields.Keyword, - SortDirection = SortDirections.Ascending, - CustomSortField = KeyWord1Name, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - - var count = 0; - foreach (var title in titles.OrderBy(s => s)) - { - Assert.AreEqual(title, search.Results[count++].Keywords[KeyWord1Name]); - } - } - - [Test] - public void SearchController_GetResult_Sorty_By_Keyword_Descending_Returns_Alphabetic_Descending() - { - var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; - - var added = this.AddDocumentsWithKeywords(titles, "animal"); - - // Act - var query = new SearchQuery - { - KeyWords = "animal", - SearchTypeIds = new List { OtherSearchTypeId }, - SortField = SortFields.Keyword, - SortDirection = SortDirections.Descending, - CustomSortField = KeyWord1Name, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - - var count = 0; - foreach (var title in titles.OrderByDescending(s => s)) - { - Assert.AreEqual(title, search.Results[count++].Keywords[KeyWord1Name]); - } - } - - [Test] - public void SearchController_GetResult_Sort_By_Unknown_StringField_In_Descending_Order_Does_Not_Throw() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.CustomStringField, - SortDirection = SortDirections.Descending, - CustomSortField = "unknown", - }; - this._searchController.SiteSearch(query); - } - - [Test] - public void SearchController_GetResult_Sort_By_Unknown_StringField_In_Ascending_Order_Does_Not_Throw() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.CustomStringField, - SortDirection = SortDirections.Ascending, - CustomSortField = "unknown", - }; - this._searchController.SiteSearch(query); - } - - [Test] - public void SearchController_GetResult_Sort_By_Unknown_NumericField_In_Descending_Order_Does_Not_Throw() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.CustomNumericField, - SortDirection = SortDirections.Descending, - CustomSortField = "unknown", - }; - this._searchController.SiteSearch(query); - } - - [Test] - public void SearchController_GetResult_Sort_By_Unknown_NumericField_In_Ascending_Order_Does_Not_Throw() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.CustomNumericField, - SortDirection = SortDirections.Ascending, - CustomSortField = "unknown", - }; - this._searchController.SiteSearch(query); - } - - [Test] - public void SearchController_GetResult_Sorty_By_Relevance_Returns_TopHit_Docs_First() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Relevance, - KeyWords = "brown OR fox", - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.AreEqual(true, search.Results[0].Snippet.Contains("brown") && search.Results[0].Snippet.Contains("dog")); - } - - [Test] - public void SearchController_GetResult_Sorty_By_RelevanceAndTitleKeyword_Returns_TopHit_Docs_First() - { - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(CustomBoost); - - // Arrange - var added = this.AddSearchDocsForCustomBoost(); - this.CreateNewLuceneControllerInstance(true); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Relevance, - KeyWords = "Hello", - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.AreEqual(true, search.Results[0].Body.Contains("Hello1")); - } - - [Test] - public void SearchController_GetResult_Sorty_By_RelevanceAndSubjectKeyword_Returns_TopHit_Docs_First() - { - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(CustomBoost); - this.CreateNewLuceneControllerInstance(true); - - // Arrange - var added = this.AddSearchDocsForCustomBoost(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Relevance, - KeyWords = "Hello", - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.AreEqual(true, search.Results[0].Body.Contains("Hello2")); - } - - [Test] - public void SearchController_GetResult_Sorty_By_RelevanceAndCommentKeyword_Returns_TopHit_Docs_First() - { - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(CustomBoost); - this.CreateNewLuceneControllerInstance(true); - - // Arrange - var added = this.AddSearchDocsForCustomBoost(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Relevance, - KeyWords = "Hello", - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.AreEqual(true, search.Results[0].Body.Contains("Hello3")); - } - - [Test] - public void SearchController_GetResult_Sorty_By_RelevanceAndAuthorKeyword_Returns_TopHit_Docs_First() - { - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(CustomBoost); - this.CreateNewLuceneControllerInstance(true); - - // Arrange - var added = this.AddSearchDocsForCustomBoost(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Relevance, - KeyWords = "Hello", - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.AreEqual(true, search.Results[0].Body.Contains("Hello4")); - } - - [Test] - public void SearchController_GetResult_Sorty_By_Relevance_Ascending_Does_Not_Change_Sequence_Of_Results() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Relevance, - SortDirection = SortDirections.Ascending, - KeyWords = "brown OR fox", - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - Assert.AreEqual(true, search.Results[0].Snippet.Contains("brown") && search.Results[0].Snippet.Contains("dog")); - } - - [Test] - public void SearchController_GetResult_By_Locale_Returns_Specific_And_Neutral_Locales() - { - // Arrange - this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.LastModified, - CultureCode = CultureItIt, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(2, search.Results.Count, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - Assert.AreEqual(Line3, search.Results[0].Title); - Assert.AreEqual(Line1, search.Results[1].Title); - } - - [Test] - public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_Content_With_Same_Key() - { - // Arrange - string[] docs = - { - Line1, - Line2, - }; - const string docKey = "key1"; - - // Act - - // Add first document - var doc1 = new SearchDocument { Title = docs[0], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - this._internalSearchController.AddSearchDocument(doc1); - - // Add second document with same key - var doc2 = new SearchDocument { Title = docs[1], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - this._internalSearchController.AddSearchDocument(doc2); - - // run luceneQuery on common keyword between both the docs - var search = this.SearchForKeyword("fox"); - - // Assert - there should just be one entry - first one must have been removed. - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual(docs[1], search.Results[0].Title); - } - - [Test] - public void SearchController_Add_Does_Not_Throw_On_Empty_Url() - { - var doc = new SearchDocument - { - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = OtherSearchTypeId, - Title = " ", - ModifiedTimeUtc = DateTime.UtcNow, - QueryString = "?foo=bar", - }; - - Assert.DoesNotThrow(() => this._internalSearchController.AddSearchDocument(doc)); - } - - [Test] - public void SearchController_Add_Does_Not_Throw_On_Empty_Title() - { - var doc = new SearchDocument - { - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - }; - - Assert.DoesNotThrow(() => this._internalSearchController.AddSearchDocument(doc)); - } - - [Test] - public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_When_IsActive_Is_False() - { - // Arrange - string[] docs = - { - Line1, - Line2, - }; - const string docKey = "key1"; - - // Act - - // Add first document - var doc1 = new SearchDocument { Title = docs[0], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - this._internalSearchController.AddSearchDocument(doc1); - - // Add second document with same key - var doc2 = new SearchDocument { Title = docs[1], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, IsActive = false }; - this._internalSearchController.AddSearchDocument(doc2); - - // run luceneQuery on common keyword between both the docs - var search = this.SearchForKeyword("fox"); - - // Assert - there should not be any record. - Assert.AreEqual(0, search.Results.Count); - } - - // Note: these tests needs to pass through the analyzer which is utilized - // in SearchControllerImpl but not LuceneControllerImpl. - [Test] - public void SearchController_SearchFindsAccentedAndNonAccentedWords() - { - // Arrange - string[] lines = - { - "zèbre or panthère", - "zebre without accent", - "panthere without accent", - }; - - this.AddLinesAsSearchDocs(lines); - - // Act - var searches1 = this.SearchForKeyword("zèbre"); - var searches2 = this.SearchForKeyword("zebre"); - - // Assert - Assert.AreEqual(2, searches1.TotalHits); - Assert.AreEqual("zèbre or panthère", this.StipEllipses(searches1.Results[0].Snippet).Trim()); - Assert.AreEqual("zebre without accent", this.StipEllipses(searches1.Results[1].Snippet).Trim()); - - Assert.AreEqual(2, searches2.TotalHits); - Assert.AreEqual("zèbre or panthère", this.StipEllipses(searches2.Results[0].Snippet).Trim()); - Assert.AreEqual("zebre without accent", this.StipEllipses(searches2.Results[1].Snippet).Trim()); - } - - [Test] - public void SearchController_PorterFilterTest() - { - // Arrange - string[] lines = - { - "field1_value", - "field2_value", - }; - - this.AddLinesAsSearchDocs(lines); - - // Act - var search1 = this.SearchForKeyword(lines[0]); - var search2 = this.SearchForKeyword("\"" + lines[1] + "\""); - - // Assert - Assert.AreEqual(1, search1.TotalHits); - Assert.AreEqual(1, search2.TotalHits); - - Assert.AreEqual("" + lines[0] + "", this.StipEllipses(search1.Results[0].Snippet).Trim()); - Assert.AreEqual("" + lines[1] + "", this.StipEllipses(search2.Results[0].Snippet).Trim()); - } - - [Test] - public void SearchController_SearchFindsStemmedWords() - { - // Arrange - string[] lines = - { - "I ride my bike to work", - "All team are riding their bikes", - "The boy rides his bike to school", - "This sentence is missing the bike ri... word", - }; - - this.AddLinesAsSearchDocs(lines); - - // Act - var search = this.SearchForKeyword("ride"); - - // Assert - Assert.AreEqual(3, search.TotalHits); - Assert.AreEqual("I ride my bike to work", this.StipEllipses(search.Results[0].Snippet)); - Assert.AreEqual("m are riding their bikes", this.StipEllipses(search.Results[1].Snippet)); - Assert.AreEqual("e boy rides his bike to school", this.StipEllipses(search.Results[2].Snippet)); - } - - [Test] - public void SearchController_Search_Synonym_Works() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var search = this.SearchForKeywordInModule("wolf"); - - // Assert - Assert.AreEqual(added, search.TotalHits); - - var snippets = search.Results.Select(result => this.StipEllipses(result.Snippet)).OrderBy(s => s).ToArray(); - Assert.AreEqual("brown fox jumps over the lazy dog", snippets[0]); - Assert.AreEqual("e red fox jumped over the lazy dark gray dog", snippets[1]); - Assert.AreEqual("gold fox jumped over the lazy black dog", snippets[2]); - Assert.AreEqual("quick fox jumps over the black dog - Italian", snippets[3]); - } - - [Test] - public void SearchController_Title_Ranked_Higher_Than_Body() - { - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "Hello World" }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "cow is gone" }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.Commit(); - - var result = this.SearchForKeyword("cow"); - - // Assert - Assert.AreEqual(result.TotalHits, 2); - Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); - Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); - } - - [Test] - public void SearchController_Title_Ranked_Higher_Than_Body_Regardless_Of_Document_Sequence() - { - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "cow is gone" }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.Commit(); - - var result = this.SearchForKeyword("cow"); - - // Assert - Assert.AreEqual(result.TotalHits, 2); - Assert.AreEqual(doc3.UniqueKey, result.Results[0].UniqueKey); - Assert.AreEqual(doc1.UniqueKey, result.Results[1].UniqueKey); - } - - [Test] - public void SearchController_Title_Ranked_Higher_Than_Tag() - { - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "Hello World" }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { "cow", "hello", "world" } }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.Commit(); - var result = this.SearchForKeyword("cow"); - - // Assert - Assert.AreEqual(result.TotalHits, 2); - Console.WriteLine("first score: {0} {1}", result.Results[0].UniqueKey, result.Results[0].DisplayScore); - Console.WriteLine("second score: {0} {1}", result.Results[1].UniqueKey, result.Results[1].DisplayScore); - Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); - Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); - } - - [Test] - public void SearchController_RankingTest_With_Vowel() - { - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "tootsie", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { "tootsie" } }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Keywords = new Dictionary() { { KeyWord1Name, "tootsie" } } }; - var doc4 = new SearchDocument { UniqueKey = "key04", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Description = "tootsie" }; - var doc5 = new SearchDocument { UniqueKey = "key05", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "hello tootsie" }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.AddSearchDocument(doc4); - this._internalSearchController.AddSearchDocument(doc5); - - this._internalSearchController.Commit(); - - var result = this.SearchForKeyword("tootsie"); - - // Assert - Assert.AreEqual(5, result.TotalHits); - foreach (var searchResult in result.Results) - { - Console.WriteLine("{0} score: {1}", searchResult.UniqueKey, searchResult.DisplayScore); - } - - Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); - Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); - Assert.AreEqual(doc3.UniqueKey, result.Results[2].UniqueKey); - Assert.AreEqual(doc4.UniqueKey, result.Results[3].UniqueKey); - } - - [Test] - public void SearchController_FileNameTest_With_WildCard() - { - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - - this._internalSearchController.Commit(); - - var result = this.SearchForKeywordWithWildCard("file"); - - // Assert - Assert.AreEqual(1, result.TotalHits); - Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); - } - - [Test] - public void SearchController_Full_FileNameTest_Without_WildCard() - { - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - - this._internalSearchController.Commit(); - - var result = this.SearchForKeywordWithWildCard("file.ext"); - - // Assert - Assert.AreEqual(1, result.TotalHits); - Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); - } - - [Test] - public void SearchController_Full_FileNameTest_With_WildCard() - { - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - - this._internalSearchController.Commit(); - - var result = this.SearchForKeyword("file.ext"); - - // Assert - Assert.AreEqual(1, result.TotalHits); - Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); - } - - [Test] - public void SearchController_Scope_By_FolderName() - { - // Arrange - this.AddFoldersAndFiles(); - - // Act - var result1 = this.SearchForKeyword("kw-folderName:Images/*"); - var result2 = this.SearchForKeyword("kw-folderName:Images/DNN/*"); - var result3 = this.SearchForKeywordWithWildCard("kw-folderName:Images/* AND spacer"); - - // Assert - Assert.AreEqual(5, result1.TotalHits); - Assert.AreEqual(2, result2.TotalHits); - Assert.AreEqual(1, result3.TotalHits); - } - - [Test] - public void SearchController_Scope_By_FolderName_With_Spaces() - { - // Arrange - this.AddFoldersAndFiles(); - - // Act - Space is replaced by < - var query1 = new SearchQuery { KeyWords = "kw-folderName:Images/*", SearchTypeIds = new[] { OtherSearchTypeId }, WildCardSearch = false }; - var query2 = new SearchQuery { KeyWords = "kw-folderName:my() { { NumericKey1, NumericValue50 } }, - SearchTypeIds = new List { OtherSearchTypeId }, - WildCardSearch = false, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual(NumericValue50, search.Results[0].NumericKeys[NumericKey1]); - } - - [Test] - public void SearchController_GetResult_Works_With_CustomKeyword_Querirs() - { - this.AddDocumentsWithKeywords(); - - // Act - var query = new SearchQuery - { - CustomKeywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } }, - SearchTypeIds = new List { OtherSearchTypeId }, - WildCardSearch = false, - }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual(KeyWord1Value, search.Results[0].Keywords[KeyWord1Name]); - } - - [Test] - public void SearchController_EnableLeadingWildcard_Should_Not_Return_Results_When_Property_Is_False() - { - this._mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("N"); - - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.Commit(); - - var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, false); - - // Assert - Assert.AreEqual(0, result.TotalHits); - } - - [Test] - public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Property_Is_True() - { - this._mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("N"); - - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.Commit(); - - var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, true); - - // Assert - Assert.AreEqual(1, result.TotalHits); - Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); - } - - [Test] - public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Property_Is_False_But_Host_Setting_Is_True() - { - this._mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("Y"); - - // Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - - // Act - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.Commit(); - - var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, false); - - // Assert - Assert.AreEqual(1, result.TotalHits); - Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); - } - - [Test] - public void SearchController_Search_StopWords_Works() - { - // Arrange - var added = this.AddStandardSearchDocs(); - this._internalSearchController.Commit(); - - // Act - var search = this.SearchForKeywordInModule("the"); - - // Assert - // the word "the" is ignored in all languages except es-ES - Assert.AreEqual(1, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - - // Act - search = this.SearchForKeywordInModule("over"); - - // Assert - // we won't find "over" in neutral, en-US, and en-CA documents, but will find it in the es-ES and it-IT documents. - Assert.AreEqual(2, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - - // Act - search = this.SearchForKeywordInModule("los"); - - // Assert - // we won't find "los" in the es-ES document. - Assert.AreEqual(0, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - } - - /// - /// Executes function proc on a separate thread respecting the given timeout value. - /// - /// - /// The function to execute. - /// The timeout duration. - /// R. - /// From: http://stackoverflow.com/questions/9460661/implementing-regex-timeout-in-net-4. - private static R ExecuteWithTimeout(Func proc, TimeSpan timeout) - { - var r = default(R); // init default return value - Exception ex = null; // records inter-thread exception - - // define a thread to wrap 'proc' - var t = new Thread(() => - { - try - { - r = proc(); - } - catch (Exception e) - { - // this can get set to ThreadAbortException - ex = e; - - Console.WriteLine("Exception hit"); - } - }); - - t.Start(); // start running 'proc' thread wrapper - - // from docs: "The Start method does not return until the new thread has started running." - if (t.Join(timeout) == false) - { - t.Abort(); // die evil thread! - - // Abort raises the ThreadAbortException - int i = 0; - while ((t.Join(1) == false) && (i < 20)) - { - // 20 ms wait possible here - i++; - } - - if (i >= 20) - { - // we didn't abort, might want to log this or take some other action - // this can happen if you are doing something indefinitely hinky in a - // finally block (cause the finally be will executed before the Abort - // completes. - Console.WriteLine("Abort didn't work as expected"); - } - } - - if (ex != null) - { - throw ex; // oops - } - - return r; // ah! - } - - private void CreateNewLuceneControllerInstance(bool reCreate = false) - { - InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); - this._internalSearchController = InternalSearchController.Instance; - this._searchController = new SearchControllerImpl(); - - if (!reCreate) - { - this.DeleteIndexFolder(); - - if (this._luceneController != null) - { - LuceneController.ClearInstance(); - this._luceneController.Dispose(); - } - - this._luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(this._luceneController); - } - } - - private void SetupHostController() - { - this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); - this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchDescriptionBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); - HostController.RegisterInstance(this._mockHostController.Object); - } - - private void SetupLocaleController() - { - this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); - - this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); - } - - private void SetupDataProvider() - { - // Standard DataProvider Path for Logging - this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - - DataTableReader searchTypes = null; - this._mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) - .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) - .Returns(() => searchTypes); - - this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); - } - - private IDataReader GetPortalsCallBack(string culture) - { - return this.GetPortalCallBack(PortalId0, CultureEnUs); - } - - private IDataReader GetPortalCallBack(int portalId, string culture) - { - var table = new DataTable("Portal"); - - var cols = new[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - const int homePage = 1; - table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, - "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, - "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", - null, homePage.ToString("D"), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); - - return table.CreateDataReader(); - } - - private void SetupSearchHelper() - { - this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); - this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.GetSynonymsCallBack); - this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); - this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); - this._mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( - new SearchStopWords - { - PortalId = 0, - CultureCode = CultureEsEs, - StopWords = "los,de,el", - }); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnUs)).Returns( - new SearchStopWords - { - PortalId = 0, - CultureCode = CultureEnUs, - StopWords = "the,over", - }); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnCa)).Returns( - new SearchStopWords - { - PortalId = 0, - CultureCode = CultureEnCa, - StopWords = "the,over", - }); - - this._mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new SearchHelperImpl().RephraseSearchText); - this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); - SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); - } - - private SearchType GetSearchTypeByNameCallback(string searchTypeName) - { - var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; - switch (searchTypeName) - { - case ModuleSearchTypeName: - searchType.SearchTypeId = ModuleSearchTypeId; - break; - case TabSearchTypeName: - searchType.SearchTypeId = TabSearchTypeId; - break; - case OtherSearchTypeName: - searchType.SearchTypeId = OtherSearchTypeId; - break; - case DocumentSearchTypeName: - searchType.SearchTypeId = DocumentSearchTypeId; - break; - case UrlSearchTypeName: - searchType.SearchTypeId = UrlSearchTypeId; - break; - } - - return searchType; - } - - private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) - { - var synonyms = new List(); - if (term == "fox") - { - synonyms.Add("wolf"); - } - - return synonyms; - } - - private UserInfo GetUserByIdCallback(int portalId, int userId) - { - if (portalId == PortalId12 && userId == StandardAuthorId) - { - return new UserInfo { UserID = userId, DisplayName = StandardAuthorDisplayName }; - } - - return null; - } - - private DataTable GetAllSearchTypes() - { - var dtSearchTypes = new DataTable("SearchTypes"); - var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); - dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); - dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); - dtSearchTypes.PrimaryKey = new[] { pkId }; - - // Create default Crawler - dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(DocumentSearchTypeId, DocumentSearchTypeName, NoPermissionFakeResultControllerClass); - dtSearchTypes.Rows.Add(UrlSearchTypeId, UrlSearchTypeName, FakeResultControllerClass); - - return dtSearchTypes; - } - - private IEnumerable GetSearchTypes() - { - var searchTypes = new List - { - new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = DocumentSearchTypeId, SearchTypeName = DocumentSearchTypeName, SearchResultClass = NoPermissionFakeResultControllerClass }, - new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, - }; - - return searchTypes; - } - - private void DeleteIndexFolder() - { - try - { - if (Directory.Exists(SearchIndexFolder)) - { - Directory.Delete(SearchIndexFolder, true); - } - } - catch (Exception ex) - { - Console.WriteLine(ex); - } - } - - /// - /// Returns few SearchDocs. - /// - private IEnumerable GetStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) - { - var searchDocs = new List - { - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag0, Tag1, TagOldest, Tag0WithSpace }, Title = Line1 }, - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag1, Tag2, TagNeutral }, Title = Line2, CultureCode = CultureEnUs }, - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line3, CultureCode = CultureItIt }, - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag3, Tag4, TagLatest }, Title = Line4, CultureCode = CultureEnCa }, - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line5, CultureCode = CultureEsEs }, - }; - - var now = DateTime.UtcNow.AddYears(-searchDocs.Count); - var i = 0; - - foreach (var searchDocument in searchDocs) - { - searchDocument.SearchTypeId = searchTypeId; - searchDocument.UniqueKey = Guid.NewGuid().ToString(); - searchDocument.ModuleId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleId : -1; - searchDocument.ModuleDefId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleDefId : -1; - searchDocument.ModifiedTimeUtc = now.AddYears(++i); // last added is the newest - } - - return searchDocs; - } - - private IEnumerable GetSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) - { - var searchDocs = new List - { - new SearchDocument { PortalId = PortalId0, Title = Line1, Keywords = { { "title", "Hello" } }, Body = "Hello1 World" }, - new SearchDocument { PortalId = PortalId0, Title = Line2, Keywords = { { "subject", "Hello" } }, Body = "Hello2 World" }, - new SearchDocument { PortalId = PortalId0, Title = Line3, Keywords = { { "comments", "Hello" } }, Body = "Hello3 World" }, - new SearchDocument { PortalId = PortalId0, Title = Line4, Keywords = { { "authorname", "Hello" } }, Body = "Hello4 World" }, - }; - - var now = DateTime.UtcNow.AddYears(-searchDocs.Count); - var i = 0; - - foreach (var searchDocument in searchDocs) - { - searchDocument.SearchTypeId = searchTypeId; - searchDocument.UniqueKey = Guid.NewGuid().ToString(); - searchDocument.ModuleId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleId : -1; - searchDocument.ModuleDefId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleDefId : -1; - searchDocument.ModifiedTimeUtc = now.AddYears(++i); // last added is the newest - } - - return searchDocs; - } - - /// - /// Adds standarad SearchDocs in Lucene Index. - /// - /// Number of dcuments added. - private int AddStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) - { - var docs = this.GetStandardSearchDocs(searchTypeId).ToArray(); - this._internalSearchController.AddSearchDocuments(docs); - return docs.Length; - } - - private int AddSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) - { - var docs = this.GetSearchDocsForCustomBoost(searchTypeId).ToArray(); - this._internalSearchController.AddSearchDocuments(docs); - return docs.Length; - } - - private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) - { - var doc1 = new SearchDocument - { - Title = "Title", - UniqueKey = "key1", - Body = "hello", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue50 } }, - }; - var doc2 = new SearchDocument - { - Title = "Title", - UniqueKey = "key2", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue100 } }, - }; - var doc3 = new SearchDocument - { - Title = "Title", - UniqueKey = "key3", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue200 } }, - }; - var doc4 = new SearchDocument - { - Title = "Title", - UniqueKey = "key4", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue500 } }, - }; - var doc5 = new SearchDocument - { - Title = "Title", - UniqueKey = "key5", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue1000 } }, - }; - - var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; - - this._internalSearchController.AddSearchDocuments(docs); - - return docs.Count; - } - - private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) - { - var doc1 = new SearchDocument - { - Title = "Title", - UniqueKey = "key1", - Body = "hello", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } }, - }; - var doc2 = new SearchDocument - { - Title = "Title", - UniqueKey = "key2", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord2Value } }, - }; - var doc3 = new SearchDocument - { - Title = "Title", - UniqueKey = "key3", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord3Value } }, - }; - var doc4 = new SearchDocument - { - Title = "Title", - UniqueKey = "key4", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord4Value } }, - }; - var doc5 = new SearchDocument - { - Title = "Title", - UniqueKey = "key5", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord5Value } }, - }; - - var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; - - this._internalSearchController.AddSearchDocuments(docs); - - return docs.Count; - } - - private int AddDocuments(IList titles, string body, int searchTypeId = OtherSearchTypeId) - { - var count = 0; - foreach (var doc in titles.Select(title => new SearchDocument - { - Title = title, - UniqueKey = Guid.NewGuid().ToString(), - Body = body, - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - })) - { - this._internalSearchController.AddSearchDocument(doc); - count++; - } - - return count; - } - - private int AddDocumentsWithKeywords(IEnumerable keywords, string title, int searchTypeId = OtherSearchTypeId) - { - var count = 0; - foreach (var doc in keywords.Select(keyword => new SearchDocument - { - Title = title, - UniqueKey = Guid.NewGuid().ToString(), - Keywords = new Dictionary() { { KeyWord1Name, keyword } }, - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - })) - { - this._internalSearchController.AddSearchDocument(doc); - count++; - } - - return count; - } - - private void AddLinesAsSearchDocs(IList lines, int searchTypeId = OtherSearchTypeId) - { - var now = DateTime.UtcNow - TimeSpan.FromSeconds(lines.Count()); - var i = 0; - - this._internalSearchController.AddSearchDocuments( - lines.Select(line => - new SearchDocument - { - Title = line, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = searchTypeId, - ModifiedTimeUtc = now.AddSeconds(i++), - }).ToList()); - } - - private SearchResults SearchForKeyword(string keyword, int searchTypeId = OtherSearchTypeId, bool useWildcard = false, bool allowLeadingWildcard = false) - { - var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = useWildcard, AllowLeadingWildcard = allowLeadingWildcard }; - return this._searchController.SiteSearch(query); - } - - private SearchResults SearchForKeywordWithWildCard(string keyword, int searchTypeId = OtherSearchTypeId) - { - var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = true }; - return this._searchController.SiteSearch(query); - } - - private SearchResults SearchForKeywordInModule(string keyword, int searchTypeId = ModuleSearchTypeId) - { - var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId } }; - return this._searchController.SiteSearch(query); - } - - private string StipEllipses(string text) - { - return text.Replace("...", string.Empty).Trim(); - } - - /// - /// Sets up some data for testing security trimming. - /// In the tests below, the users will have access to the follwoing documents - /// { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29, ..., etc. } - /// The tests check that pagination qith various page sizes returns the proper groupings. - /// - private void SetupSecurityTrimmingDocs(int totalDocs, int searchType = DocumentSearchTypeId) - { - var docModifyTime = DateTime.UtcNow - TimeSpan.FromSeconds(totalDocs); - for (var i = 0; i < totalDocs; i++) - { - this._internalSearchController.AddSearchDocument(new SearchDocument - { - AuthorUserId = i, - Title = "Fox and Dog", - Body = Line1, - Tags = new[] { Tag0, Tag1 }, - SearchTypeId = searchType, - UniqueKey = Guid.NewGuid().ToString(), - ModifiedTimeUtc = docModifyTime.AddSeconds(i), - }); - } - } - - private void AddFoldersAndFiles() - { - var allFiles = new Dictionary - { - { "Awesome-Cycles-Logo.png", "Images/" }, - { "Banner1.jpg", "Images/" }, - { "Banner2.jpg", "Images/" }, - { "bike-powered.png", "Images/DNN/" }, - { "Spacer.gif", "Images/DNN/" }, - { "monday.png", "My { { "folderName", file.Value.ToLowerInvariant() } }, - }; - this._internalSearchController.AddSearchDocument(doc); - } - - this._internalSearchController.Commit(); - } - } -} + + using Moq; + + using NUnit.Framework; + + using Constants = DotNetNuke.Services.Search.Internals.Constants; + + /// + /// Testing various aspects of SearchController. + /// + [TestFixture] + public class SearchControllerTests + { + private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; + private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; + private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; + private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; + private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; + private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; + private const int PortalId0 = 0; + private const int PortalId12 = 12; + private const int IdeasModuleDefId = 201; + private const int BlogsoduleDefId = 202; + private const int AnswersModuleDefId = 203; + private const int HtmlModuleDefId = 20; + private const int HtmlModuleId = 25; + private const int IdeasModuleId = 301; + private const int BlogsModuleId = 302; + private const int AnswersModuleId = 303; + private const int RoleId731 = 731; + private const int RoleId532 = 532; + private const int RoleId0 = 0; + private const string Tag0 = "tag0"; + private const string Tag0WithSpace = "tag0 hello"; + private const string Tag1 = "tag1"; + private const string Tag2 = "tag2"; + private const string Tag3 = "tag3"; + private const string Tag4 = "tag4"; + private const string TagTootsie = "tootsie"; + private const string TagLatest = "latest"; + private const string TagOldest = "oldest"; + private const string TagIt = "IT"; + private const string TagNeutral = "Neutral"; + private const string ModuleSearchTypeName = "module"; + private const string OtherSearchTypeName = "other"; + private const string TabSearchTypeName = "tab"; + private const string DocumentSearchTypeName = "document"; + private const string UrlSearchTypeName = "url"; + private const string ModuleResultControllerClass = "DotNetNuke.Services.Search.Crawlers.ModuleResultController, DotNetNuke"; + private const string FakeResultControllerClass = "DotNetNuke.Tests.Core.Controllers.Search.FakeResultController, DotNetNuke.Tests.Core"; + private const string NoPermissionFakeResultControllerClass = "DotNetNuke.Tests.Core.Controllers.Search.NoPermissionFakeResultController, DotNetNuke.Tests.Core"; + private const string CultureEnUs = "en-US"; + private const string CultureEnCa = "en-CA"; + private const string CultureItIt = "it-IT"; + private const string CultureEsEs = "es-ES"; + private const int LanguageIdEnUs = 1; + private const int LanguageIdEnFr = 2; + private const int LanguageIdItIt = 3; + private const int LanguageIdEsEs = 4; + private const int StandardAuthorId = 55; + private const int StandardRoleId = 66; + private const string StandardAuthorDisplayName = "Standard User"; + private const int StandardTabId = 99; + private const string StandardPermission = "!Translator (en-US);![4];[5];[6];Administrators;ContentEditorRole;"; + private const string StandardQueryString = "cid=1"; + private const string NumericKey1 = "numerickey1"; + private const string NumericKey2 = "numerickey2"; + private const int NumericValue1 = 77777; + private const int NumericValue2 = 55555; + private const int NumericValue50 = 50; + private const int NumericValue100 = 100; + private const int NumericValue200 = 200; + private const int NumericValue500 = 500; + private const int NumericValue1000 = 1000; + private const string KeyWord1Name = "keyword1"; + private const string KeyWord1Value = "value1"; + private const string KeyWord2Name = "keyword2"; + private const string KeyWord2Value = "value2"; + private const string KeyWord3Value = "value3"; + private const string KeyWord4Value = "value4"; + private const string KeyWord5Value = "value5"; + private const string Line1 = "The quick brown fox jumps over the lazy dog"; + private const string Line2 = "The quick gold fox jumped over the lazy black dog"; + private const string Line3 = "the quick fox jumps over the black dog - Italian"; + private const string Line4 = "the red fox jumped over the lazy dark gray dog"; + private const string Line5 = "the quick fox jumps over the white dog - los de el Espana"; + + private const int CustomBoost = 80; + + private const string SearchIndexFolder = @"App_Data\SearchTests"; + private const int DefaultSearchRetryTimes = 5; + private readonly double readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; + private Mock mockHostController; + private Mock mockCachingProvider; + private Mock mockDataProvider; + private Mock mockLocaleController; + private Mock mockSearchHelper; + private Mock mockUserController; + + private SearchControllerImpl searchController; + private IInternalSearchController internalSearchController; + private LuceneControllerImpl luceneController; + + public enum SearchTypeIds + { + ModuleSearchTypeId = 1, + TabSearchTypeId, + DocumentSearchTypeId, + UrlSearchTypeId, + OtherSearchTypeId, + UnknownSearchTypeId, + } + + [SetUp] + public void SetUp() + { + ComponentFactory.Container = new SimpleContainer(); + MockComponentProvider.ResetContainer(); + + this.mockDataProvider = MockComponentProvider.CreateDataProvider(); + this.mockLocaleController = MockComponentProvider.CreateLocaleController(); + this.mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); + + this.mockUserController = new Mock(); + this.mockHostController = new Mock(); + this.mockSearchHelper = new Mock(); + + this.SetupDataProvider(); + this.SetupHostController(); + this.SetupSearchHelper(); + this.SetupLocaleController(); + + this.mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns((int portalId, int userId) => this.GetUserByIdCallback(portalId, userId)); + UserController.SetTestableInstance(this.mockUserController.Object); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); + serviceCollection.AddTransient(container => (IHostSettingsService)this.mockHostController.Object); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + this.CreateNewLuceneControllerInstance(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + this.luceneController.Dispose(); + this.DeleteIndexFolder(); + InternalSearchController.ClearInstance(); + UserController.ClearInstance(); + SearchHelper.ClearInstance(); + LuceneController.ClearInstance(); + this.luceneController = null; + Globals.DependencyProvider = null; + } + + [Test] + public void SearchController_Search_Throws_On_Null_Query() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this.searchController.SiteSearch(null)); + } + + [Test] + public void SearchController_Search_Throws_On_Empty_TypeId_Collection() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this.searchController.SiteSearch(new SearchQuery { KeyWords = "word" })); + } + + [Test] + public void SearchController_AddSearchDcoumet_Regex_Does_Not_Sleep_On_Bad_Text_During_Alt_Text_Parsing() + { + // Arrange + var document = new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "< ExecuteWithTimeout( + () => + { + this.internalSearchController.AddSearchDocument(document); + return false; + }, TimeSpan.FromSeconds(1))); + } + + [Test] + public void SearchController_Added_Item_IsRetrieved() + { + // Arrange + var doc = new SearchDocument { UniqueKey = "key01", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + + // Act + this.internalSearchController.AddSearchDocument(doc); + + var result = this.SearchForKeyword("hello"); + + // Assert + Assert.AreEqual(1, result.Results.Count); + Assert.AreEqual(result.Results[0].UniqueKey, doc.UniqueKey); + Assert.AreEqual(result.Results[0].Title, doc.Title); + } + + [Test] + public void SearchController_EnsureIndexIsAppended_When_Index_Is_NotDeleted_InBetween() + { + // Arrange + string[] docs = + { + Line1, + Line2, + }; + + // Act + + // Add first document + var doc1 = new SearchDocument { Title = docs[0], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + this.internalSearchController.AddSearchDocument(doc1); + + // first luceneQuery + var query1 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; + var search1 = this.searchController.SiteSearch(query1); + + // Assert + Assert.AreEqual(1, search1.Results.Count); + + // Add second document + var doc2 = new SearchDocument { Title = docs[1], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + this.internalSearchController.AddSearchDocument(doc2); + this.CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion + + // second luceneQuery + var query2 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; + var search2 = this.searchController.SiteSearch(query2); + + // Assert + Assert.AreEqual(2, search2.Results.Count); + } + + [Test] + public void SearchController_Getsearch_TwoTermsSearch() + { + // Arrange + string[] docs = + { + Line1, + Line2, + Line3, + Line4, + Line5, + }; + + this.AddLinesAsSearchDocs(docs); + + // Act + var search = this.SearchForKeyword("fox jumps"); + + // Assert + Assert.AreEqual(docs.Length, search.Results.Count); + + // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); + // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); + } + + [Test] + public void SearchController_GetResult_TwoTermsSearch() + { + // Arrange + string[] docs = + { + Line1, + Line2, + Line3, + Line4, + Line5, + }; + + this.AddLinesAsSearchDocs(docs); + + // Act + var search = this.SearchForKeyword("fox jumps"); + + // Assert + Assert.AreEqual(docs.Length, search.Results.Count); + + // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); + // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); + } + + [Test] + public void SearchController_GetResult_PortalIdSearch() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, PortalIds = new List { PortalId0 } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + } + + [Test] + public void SearchController_GetResult_SearchTypeIdSearch() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + } + + [Test] + public void SearchController_SearchFindsAnalyzedVeryLongWords() + { + // Arrange + // const string fieldName = Constants.ContentTag; + const string veryLongWord = // 107 characters + "NowIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountryalsoIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountry"; + + var doc = new SearchDocument + { + Title = veryLongWord, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = ModuleSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + ModuleId = 1, + ModuleDefId = 1, + }; + this.internalSearchController.AddSearchDocument(doc); + + // Act + var query = new SearchQuery { KeyWords = veryLongWord, SearchTypeIds = new List { ModuleSearchTypeId } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual("" + veryLongWord + "", this.StipEllipses(search.Results[0].Snippet).Trim()); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsNoResultsWhenHavingNoPermission() + { + // Arrange + this.AddStandardSearchDocs(DocumentSearchTypeId); + + // Act + var result = this.SearchForKeyword("fox", DocumentSearchTypeId); + + // Assert + // by default AuthorUserId = 0 which have no permission, so this passes + Assert.AreEqual(0, result.Results.Count); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1A() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 1, + PageSize = 4, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(new[] { 6, 7, 8, 9 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1B() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 1, + PageSize = 6, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1C() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 1, + PageSize = 8, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1D() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; // user should have access to some documnets here + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 1, + PageSize = 100, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(4 * 3, result.TotalHits); + Assert.AreEqual(4 * 3, result.Results.Count); + Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1E() + { + // Arrange + const int maxDocs = 30; + const int stype = TabSearchTypeId; // user should have access to all documnets here + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 1, + PageSize = 10, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).Skip(1).ToArray(); + + // Assert + Assert.AreEqual(maxDocs, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(Enumerable.Range(1, 9).ToArray(), ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1F() + { + // Arrange + const int maxDocs = 100; + const int stype = TabSearchTypeId; // user should have access to all documnets here + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 10, + PageSize = 10, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(Enumerable.Range(90, 10).ToArray(), ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2A() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 2, + PageSize = 5, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(5, result.Results.Count); + Assert.AreEqual(new[] { 17, 18, 19, 26, 27 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2B() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 2, + PageSize = 6, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(6, result.Results.Count); + Assert.AreEqual(new[] { 18, 19, 26, 27, 28, 29 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2C() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery + { + PageIndex = 2, + PageSize = 8, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(4, result.Results.Count); + Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3A() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var queryPg3 = new SearchQuery + { + PageIndex = 3, + PageSize = 4, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(queryPg3); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(queryPg3.PageSize, result.Results.Count); + Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3B() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var queryPg3 = new SearchQuery + { + PageIndex = 3, + PageSize = 5, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(queryPg3); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(2, result.Results.Count); + Assert.AreEqual(new[] { 28, 29 }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3C() + { + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var queryPg3 = new SearchQuery + { + PageIndex = 3, + PageSize = 8, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(queryPg3); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(0, result.Results.Count); + Assert.AreEqual(new int[] { }, ids); + } + + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage5() + { + // Arrange + const int maxDocs = 100; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var queryPg3 = new SearchQuery + { + PageIndex = 5, + PageSize = 8, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this.searchController.SiteSearch(queryPg3); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - (10 * 6), result.TotalHits); + Assert.AreEqual(queryPg3.PageSize, result.Results.Count); + Assert.AreEqual(new int[] { 86, 87, 88, 89, 96, 97, 98, 99 }, ids); + } + + [Test] + public void SearchController_GetResult_Returns_Correct_SuppliedData_When_Optionals_Are_Supplied() + { + // Arrange + var modifiedDateTime = DateTime.UtcNow; + var numericKeys = new Dictionary() { { NumericKey1, NumericValue1 }, { NumericKey2, NumericValue2 } }; + var keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value }, { KeyWord2Name, KeyWord2Value } }; + var tags = new List { Tag1, Tag2 }; + var doc = new SearchDocument + { + Title = "Title", + UniqueKey = "key", + SearchTypeId = ModuleSearchTypeId, + ModifiedTimeUtc = modifiedDateTime, + PortalId = PortalId12, + TabId = StandardTabId, + ModuleDefId = HtmlModuleDefId, + ModuleId = HtmlModuleId, + Description = "Description", + Body = "Body", + AuthorUserId = StandardAuthorId, + RoleId = StandardRoleId, + Permissions = StandardPermission, + QueryString = StandardQueryString, + Tags = tags, + NumericKeys = numericKeys, + Keywords = keywords, + }; + this.internalSearchController.AddSearchDocument(doc); + + // run luceneQuery on common keyword between both the docs + var search = this.SearchForKeywordInModule("Title"); + + // Assert + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual(PortalId12, search.Results[0].PortalId); + Assert.AreEqual(StandardTabId, search.Results[0].TabId); + Assert.AreEqual(HtmlModuleDefId, search.Results[0].ModuleDefId); + Assert.AreEqual(HtmlModuleId, search.Results[0].ModuleId); + Assert.AreEqual(ModuleSearchTypeId, search.Results[0].SearchTypeId); + Assert.AreEqual("Description", search.Results[0].Description); + Assert.AreEqual("Body", search.Results[0].Body); + Assert.AreEqual(StandardAuthorId, search.Results[0].AuthorUserId); + Assert.AreEqual(StandardRoleId, search.Results[0].RoleId); + Assert.AreEqual(modifiedDateTime.ToString(Constants.DateTimeFormat), search.Results[0].ModifiedTimeUtc.ToString(Constants.DateTimeFormat)); + Assert.AreEqual(StandardPermission, search.Results[0].Permissions); + Assert.AreEqual(StandardQueryString, search.Results[0].QueryString); + Assert.AreEqual(StandardAuthorDisplayName, search.Results[0].AuthorName); + Assert.AreEqual(tags.Count, search.Results[0].Tags.Count()); + Assert.AreEqual(tags[0], search.Results[0].Tags.ElementAt(0)); + Assert.AreEqual(tags[1], search.Results[0].Tags.ElementAt(1)); + Assert.AreEqual(numericKeys.Count, search.Results[0].NumericKeys.Count); + Assert.AreEqual(numericKeys[NumericKey1], search.Results[0].NumericKeys[NumericKey1]); + Assert.AreEqual(numericKeys[NumericKey2], search.Results[0].NumericKeys[NumericKey2]); + Assert.AreEqual(keywords.Count, search.Results[0].Keywords.Count); + Assert.AreEqual(keywords[KeyWord1Name], search.Results[0].Keywords[KeyWord1Name]); + Assert.AreEqual(keywords[KeyWord2Name], search.Results[0].Keywords[KeyWord2Name]); + } + + [Test] + public void SearchController_GetResult_Returns_EmptyData_When_Optionals_Are_Not_Supplied() + { + // Arrange + var modifiedDateTime = DateTime.UtcNow; + var doc = new SearchDocument + { + PortalId = PortalId0, + Title = "Title", + UniqueKey = "key", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = modifiedDateTime, + }; + this.internalSearchController.AddSearchDocument(doc); + + var search = this.SearchForKeyword("Title"); + + // Assert - + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual(PortalId0, search.Results[0].PortalId); + Assert.AreEqual(0, search.Results[0].TabId); + Assert.AreEqual(0, search.Results[0].ModuleDefId); + Assert.AreEqual(0, search.Results[0].ModuleId); + Assert.AreEqual(OtherSearchTypeId, search.Results[0].SearchTypeId); + Assert.AreEqual(null, search.Results[0].Description); + Assert.AreEqual(null, search.Results[0].Body); + Assert.AreEqual(0, search.Results[0].AuthorUserId); + Assert.AreEqual(-1, search.Results[0].RoleId); + Assert.AreEqual(modifiedDateTime.ToString(Constants.DateTimeFormat), search.Results[0].ModifiedTimeUtc.ToString(Constants.DateTimeFormat)); + Assert.AreEqual(null, search.Results[0].Permissions); + Assert.AreEqual(null, search.Results[0].QueryString); + Assert.AreEqual(null, search.Results[0].AuthorName); + Assert.AreEqual(0, search.Results[0].Tags.Count()); + Assert.AreEqual(0, search.Results[0].NumericKeys.Count); + Assert.AreEqual(0, search.Results[0].Keywords.Count); + } + + [Test] + public void SearchController_GetsHighlightedDesc() + { + // Arrange + string[] docs = + { + Line1, + Line2, + Line3, + Line4, + Line5, + }; + this.AddLinesAsSearchDocs(docs); + + // Act + var search = this.SearchForKeyword("fox"); + + // Assert + Assert.AreEqual(docs.Length, search.Results.Count); + Assert.IsTrue( + new[] + { + "brown fox jumps over the lazy dog", + "quick fox jumps over the black dog - Italian", + "gold fox jumped over the lazy black dog", + "e red fox jumped over the lazy dark gray dog", + "quick fox jumps over the white dog - los de el Espana", + }.SequenceEqual(search.Results.Select(r => this.StipEllipses(r.Snippet))), + "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Snippet))); + } + + [Test] + public void SearchController_CorrectDocumentCultureIsUsedAtIndexing() + { + // Arrange + // assign a culture that is different than the current one + var isNonEnglishEnv = Thread.CurrentThread.CurrentCulture.Name != CultureEsEs; + string cultureCode, title, searchWord; + + // Act + if (isNonEnglishEnv) + { + cultureCode = CultureEsEs; + searchWord = "zorro"; + title = "los rápidos saltos de zorro sobre el perro negro"; + } + else + { + cultureCode = CultureEnUs; + searchWord = "fox"; + title = Line3; + } + + this.internalSearchController.AddSearchDocument( + new SearchDocument + { + Title = title, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + CultureCode = cultureCode, + }); + this.internalSearchController.Commit(); + + var searches = this.SearchForKeyword(searchWord); + + // Assert + Assert.AreEqual(1, searches.TotalHits); + Assert.AreEqual(cultureCode, searches.Results[0].CultureCode); + } + + [Test] + public void SearchController_GetResult_TimeRangeSearch_Ignores_When_Only_BeginDate_Specified() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, BeginModifiedTimeUtc = DateTime.Now }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + } + + [Test] + public void SearchController_GetResult_TimeRangeSearch_Resturns_Scoped_Results_When_BeginDate_Is_After_End_Date() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + BeginModifiedTimeUtc = DateTime.Now, + EndModifiedTimeUtc = DateTime.Now.AddSeconds(-1), + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + } + + [Test] + public void SearchController_GetResult_TimeRangeSearch_Resturns_Scoped_Results_When_Both_Dates_Specified() + { + // Arrange + var added = this.AddStandardSearchDocs(); + var stypeIds = new List { ModuleSearchTypeId }; + var utcNow = DateTime.UtcNow.AddDays(1); + const SortFields sfield = SortFields.LastModified; + + // Act and Assert - just a bit later + var query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddSeconds(1), EndModifiedTimeUtc = utcNow.AddDays(1) }; + var search = this.searchController.SiteSearch(query); + Assert.AreEqual(0, search.Results.Count); + + // Act and Assert - 10 day + query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-10), EndModifiedTimeUtc = utcNow.AddDays(1) }; + search = this.searchController.SiteSearch(query); + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual(Line5, search.Results[0].Title); + + // Act and Assert - 1 year or so + query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-368), EndModifiedTimeUtc = utcNow.AddDays(1) }; + search = this.searchController.SiteSearch(query); + Assert.AreEqual(2, search.Results.Count); + Assert.AreEqual(Line5, search.Results[0].Title); + Assert.AreEqual(Line4, search.Results[1].Title); + + // Act and Assert - 2 years or so + query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-800), EndModifiedTimeUtc = utcNow.AddDays(1) }; + search = this.searchController.SiteSearch(query); + Assert.AreEqual(3, search.Results.Count); + Assert.AreEqual(Line5, search.Results[0].Title); + Assert.AreEqual(Line4, search.Results[1].Title); + Assert.AreEqual(Line3, search.Results[2].Title); + + // Act and Assert - 3 years or so + query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-1200), EndModifiedTimeUtc = utcNow.AddDays(1) }; + search = this.searchController.SiteSearch(query); + Assert.AreEqual(4, search.Results.Count); + Assert.AreEqual(Line5, search.Results[0].Title); + Assert.AreEqual(Line4, search.Results[1].Title); + Assert.AreEqual(Line3, search.Results[2].Title); + Assert.AreEqual(Line2, search.Results[3].Title); + + // Act and Assert - 2 to 3 years or so + query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-1200), EndModifiedTimeUtc = utcNow.AddDays(-800) }; + search = this.searchController.SiteSearch(query); + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual(Line2, search.Results[0].Title); + } + + [Test] + public void SearchController_GetResult_TagSearch_Single_Tag_Returns_Single_Result() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0 } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(1, search.Results.Count); + } + + [Test] + public void SearchController_GetResult_TagSearch_Single_Tag_With_Space_Returns_Single_Result() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0WithSpace } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(1, search.Results.Count); + } + + [Test] + public void SearchController_GetResult_TagSearch_Lowercase_Search_Returns_PropercaseTag_Single_Result() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { TagNeutral.ToLowerInvariant() } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(1, search.Results.Count); + } + + [Test] + public void SearchController_GetResult_TagSearch_Single_Tag_Returns_Two_Results() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag1 } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(2, search.Results.Count); + Assert.AreEqual(Tag0, search.Results[0].Tags.ElementAt(0)); + Assert.AreEqual(Tag1, search.Results[0].Tags.ElementAt(1)); + Assert.AreEqual(Tag1, search.Results[1].Tags.ElementAt(0)); + Assert.AreEqual(Tag2, search.Results[1].Tags.ElementAt(1)); + } + + [Test] + public void SearchController_GetResult_TagSearch_Two_Tags_Returns_Nothing() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0, Tag4 } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(0, search.Results.Count); + } + + [Test] + public void SearchController_GetResult_TagSearch_Two_Tags_Returns_Single_Results() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag1, Tag2 } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual(Tag1, search.Results[0].Tags.ElementAt(0)); + Assert.AreEqual(Tag2, search.Results[0].Tags.ElementAt(1)); + } + + [Test] + public void SearchController_GetResult_TagSearch_With_Vowel_Tags_Returns_Data() + { + // Arrange + const string keyword = "awesome"; + var doc1 = new SearchDocument { UniqueKey = "key01", Title = keyword, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { TagTootsie } }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { OtherSearchTypeId }, Tags = new List { TagTootsie } }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(1, search.Results.Count); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SearchController_GetResult_Throws_When_CustomNumericField_Is_Specified_And_CustomSortField_Is_Not() + { + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.CustomNumericField, + }; + + this.searchController.SiteSearch(query); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SearchController_GetResult_Throws_When_CustomStringField_Is_Specified_And_CustomSortField_Is_Not() + { + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.CustomStringField, + }; + + this.searchController.SiteSearch(query); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SearchController_GetResult_Throws_When_NumericKey_Is_Specified_And_CustomSortField_Is_Not() + { + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.NumericKey, + }; + + this.searchController.SiteSearch(query); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void SearchController_GetResult_Throws_When_Keyword_Is_Specified_And_CustomSortField_Is_Not() + { + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Keyword, + }; + + this.searchController.SiteSearch(query); + } + + [Test] + public void SearchController_GetResult_Sorty_By_Date_Returns_Latest_Docs_First() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.LastModified, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); + + Assert.AreEqual(Tag3, search.Results[1].Tags.ElementAt(0)); + Assert.AreEqual(Tag4, search.Results[1].Tags.ElementAt(1)); + Assert.AreEqual(TagLatest, search.Results[1].Tags.ElementAt(2)); + + Assert.AreEqual(Tag2, search.Results[0].Tags.ElementAt(0)); + Assert.AreEqual(Tag3, search.Results[0].Tags.ElementAt(1)); + Assert.AreEqual(TagIt.ToLowerInvariant(), search.Results[0].Tags.ElementAt(2)); + } + + [Test] + public void SearchController_GetResult_Sorty_By_Date_Ascending_Returns_Earliest_Docs_First() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.LastModified, + SortDirection = SortDirections.Ascending, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.Greater(search.Results[1].DisplayModifiedTime, search.Results[0].DisplayModifiedTime); + Assert.Greater(search.Results[2].DisplayModifiedTime, search.Results[1].DisplayModifiedTime); + Assert.Greater(search.Results[3].DisplayModifiedTime, search.Results[2].DisplayModifiedTime); + + Assert.AreEqual(Tag0, search.Results[0].Tags.ElementAt(0)); + Assert.AreEqual(Tag1, search.Results[0].Tags.ElementAt(1)); + Assert.AreEqual(TagOldest, search.Results[0].Tags.ElementAt(2)); + } + + [Test] + public void SearchController_GetResult_Sorty_By_NumericKeys_Ascending_Returns_Smaller_Numers_First() + { + var added = this.AddDocumentsWithNumericKeys(); + + // Act + var query = new SearchQuery + { + KeyWords = "Title", + SearchTypeIds = new List { OtherSearchTypeId }, + SortField = SortFields.NumericKey, + SortDirection = SortDirections.Ascending, + CustomSortField = NumericKey1, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.Greater(search.Results[1].NumericKeys[NumericKey1], search.Results[0].NumericKeys[NumericKey1]); + Assert.Greater(search.Results[2].NumericKeys[NumericKey1], search.Results[1].NumericKeys[NumericKey1]); + } + + [Test] + public void SearchController_GetResult_Sorty_By_NumericKeys_Descending_Returns_Bigger_Numbers_First() + { + var added = this.AddDocumentsWithNumericKeys(); + + // Act + var query = new SearchQuery + { + KeyWords = "Title", + SearchTypeIds = new List { OtherSearchTypeId }, + SortField = SortFields.NumericKey, + SortDirection = SortDirections.Descending, + CustomSortField = NumericKey1, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.Greater(search.Results[0].NumericKeys[NumericKey1], search.Results[1].NumericKeys[NumericKey1]); + Assert.Greater(search.Results[1].NumericKeys[NumericKey1], search.Results[2].NumericKeys[NumericKey1]); + } + + [Test] + public void SearchController_GetResult_Sorty_By_Title_Ascending_Returns_Alphabetic_Ascending() + { + var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; + + var added = this.AddDocuments(titles, "animal"); + + // Act + var query = new SearchQuery + { + KeyWords = "animal", + SearchTypeIds = new List { OtherSearchTypeId }, + SortField = SortFields.Title, + SortDirection = SortDirections.Ascending, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + + var count = 0; + foreach (var title in titles.OrderBy(s => s)) + { + Assert.AreEqual(title, search.Results[count++].Title); + } + } + + [Test] + public void SearchController_GetResult_Sorty_By_Title_Descending_Returns_Alphabetic_Descending() + { + var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; + + var added = this.AddDocuments(titles, "animal"); + + // Act + var query = new SearchQuery + { + KeyWords = "animal", + SearchTypeIds = new List { OtherSearchTypeId }, + SortField = SortFields.Title, + SortDirection = SortDirections.Descending, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + + var count = 0; + foreach (var title in titles.OrderByDescending(s => s)) + { + Assert.AreEqual(title, search.Results[count++].Title); + } + } + + [Test] + public void SearchController_GetResult_Sorty_By_Keyword_Ascending_Returns_Alphabetic_Ascending() + { + var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; + + var added = this.AddDocumentsWithKeywords(titles, "animal"); + + // Act + var query = new SearchQuery + { + KeyWords = "animal", + SearchTypeIds = new List { OtherSearchTypeId }, + SortField = SortFields.Keyword, + SortDirection = SortDirections.Ascending, + CustomSortField = KeyWord1Name, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + + var count = 0; + foreach (var title in titles.OrderBy(s => s)) + { + Assert.AreEqual(title, search.Results[count++].Keywords[KeyWord1Name]); + } + } + + [Test] + public void SearchController_GetResult_Sorty_By_Keyword_Descending_Returns_Alphabetic_Descending() + { + var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; + + var added = this.AddDocumentsWithKeywords(titles, "animal"); + + // Act + var query = new SearchQuery + { + KeyWords = "animal", + SearchTypeIds = new List { OtherSearchTypeId }, + SortField = SortFields.Keyword, + SortDirection = SortDirections.Descending, + CustomSortField = KeyWord1Name, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + + var count = 0; + foreach (var title in titles.OrderByDescending(s => s)) + { + Assert.AreEqual(title, search.Results[count++].Keywords[KeyWord1Name]); + } + } + + [Test] + public void SearchController_GetResult_Sort_By_Unknown_StringField_In_Descending_Order_Does_Not_Throw() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.CustomStringField, + SortDirection = SortDirections.Descending, + CustomSortField = "unknown", + }; + this.searchController.SiteSearch(query); + } + + [Test] + public void SearchController_GetResult_Sort_By_Unknown_StringField_In_Ascending_Order_Does_Not_Throw() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.CustomStringField, + SortDirection = SortDirections.Ascending, + CustomSortField = "unknown", + }; + this.searchController.SiteSearch(query); + } + + [Test] + public void SearchController_GetResult_Sort_By_Unknown_NumericField_In_Descending_Order_Does_Not_Throw() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.CustomNumericField, + SortDirection = SortDirections.Descending, + CustomSortField = "unknown", + }; + this.searchController.SiteSearch(query); + } + + [Test] + public void SearchController_GetResult_Sort_By_Unknown_NumericField_In_Ascending_Order_Does_Not_Throw() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.CustomNumericField, + SortDirection = SortDirections.Ascending, + CustomSortField = "unknown", + }; + this.searchController.SiteSearch(query); + } + + [Test] + public void SearchController_GetResult_Sorty_By_Relevance_Returns_TopHit_Docs_First() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Relevance, + KeyWords = "brown OR fox", + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.AreEqual(true, search.Results[0].Snippet.Contains("brown") && search.Results[0].Snippet.Contains("dog")); + } + + [Test] + public void SearchController_GetResult_Sorty_By_RelevanceAndTitleKeyword_Returns_TopHit_Docs_First() + { + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(CustomBoost); + + // Arrange + var added = this.AddSearchDocsForCustomBoost(); + this.CreateNewLuceneControllerInstance(true); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Relevance, + KeyWords = "Hello", + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.AreEqual(true, search.Results[0].Body.Contains("Hello1")); + } + + [Test] + public void SearchController_GetResult_Sorty_By_RelevanceAndSubjectKeyword_Returns_TopHit_Docs_First() + { + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(CustomBoost); + this.CreateNewLuceneControllerInstance(true); + + // Arrange + var added = this.AddSearchDocsForCustomBoost(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Relevance, + KeyWords = "Hello", + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.AreEqual(true, search.Results[0].Body.Contains("Hello2")); + } + + [Test] + public void SearchController_GetResult_Sorty_By_RelevanceAndCommentKeyword_Returns_TopHit_Docs_First() + { + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(CustomBoost); + this.CreateNewLuceneControllerInstance(true); + + // Arrange + var added = this.AddSearchDocsForCustomBoost(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Relevance, + KeyWords = "Hello", + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.AreEqual(true, search.Results[0].Body.Contains("Hello3")); + } + + [Test] + public void SearchController_GetResult_Sorty_By_RelevanceAndAuthorKeyword_Returns_TopHit_Docs_First() + { + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(CustomBoost); + this.CreateNewLuceneControllerInstance(true); + + // Arrange + var added = this.AddSearchDocsForCustomBoost(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Relevance, + KeyWords = "Hello", + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.AreEqual(true, search.Results[0].Body.Contains("Hello4")); + } + + [Test] + public void SearchController_GetResult_Sorty_By_Relevance_Ascending_Does_Not_Change_Sequence_Of_Results() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Relevance, + SortDirection = SortDirections.Ascending, + KeyWords = "brown OR fox", + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); + Assert.AreEqual(true, search.Results[0].Snippet.Contains("brown") && search.Results[0].Snippet.Contains("dog")); + } + + [Test] + public void SearchController_GetResult_By_Locale_Returns_Specific_And_Neutral_Locales() + { + // Arrange + this.AddStandardSearchDocs(); + + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.LastModified, + CultureCode = CultureItIt, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(2, search.Results.Count, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); + Assert.AreEqual(Line3, search.Results[0].Title); + Assert.AreEqual(Line1, search.Results[1].Title); + } + + [Test] + public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_Content_With_Same_Key() + { + // Arrange + string[] docs = + { + Line1, + Line2, + }; + const string docKey = "key1"; + + // Act + + // Add first document + var doc1 = new SearchDocument { Title = docs[0], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + this.internalSearchController.AddSearchDocument(doc1); + + // Add second document with same key + var doc2 = new SearchDocument { Title = docs[1], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + this.internalSearchController.AddSearchDocument(doc2); + + // run luceneQuery on common keyword between both the docs + var search = this.SearchForKeyword("fox"); + + // Assert - there should just be one entry - first one must have been removed. + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual(docs[1], search.Results[0].Title); + } + + [Test] + public void SearchController_Add_Does_Not_Throw_On_Empty_Url() + { + var doc = new SearchDocument + { + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = OtherSearchTypeId, + Title = " ", + ModifiedTimeUtc = DateTime.UtcNow, + QueryString = "?foo=bar", + }; + + Assert.DoesNotThrow(() => this.internalSearchController.AddSearchDocument(doc)); + } + + [Test] + public void SearchController_Add_Does_Not_Throw_On_Empty_Title() + { + var doc = new SearchDocument + { + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + }; + + Assert.DoesNotThrow(() => this.internalSearchController.AddSearchDocument(doc)); + } + + [Test] + public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_When_IsActive_Is_False() + { + // Arrange + string[] docs = + { + Line1, + Line2, + }; + const string docKey = "key1"; + + // Act + + // Add first document + var doc1 = new SearchDocument { Title = docs[0], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + this.internalSearchController.AddSearchDocument(doc1); + + // Add second document with same key + var doc2 = new SearchDocument { Title = docs[1], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, IsActive = false }; + this.internalSearchController.AddSearchDocument(doc2); + + // run luceneQuery on common keyword between both the docs + var search = this.SearchForKeyword("fox"); + + // Assert - there should not be any record. + Assert.AreEqual(0, search.Results.Count); + } + + // Note: these tests needs to pass through the analyzer which is utilized + // in SearchControllerImpl but not LuceneControllerImpl. + [Test] + public void SearchController_SearchFindsAccentedAndNonAccentedWords() + { + // Arrange + string[] lines = + { + "zèbre or panthère", + "zebre without accent", + "panthere without accent", + }; + + this.AddLinesAsSearchDocs(lines); + + // Act + var searches1 = this.SearchForKeyword("zèbre"); + var searches2 = this.SearchForKeyword("zebre"); + + // Assert + Assert.AreEqual(2, searches1.TotalHits); + Assert.AreEqual("zèbre or panthère", this.StipEllipses(searches1.Results[0].Snippet).Trim()); + Assert.AreEqual("zebre without accent", this.StipEllipses(searches1.Results[1].Snippet).Trim()); + + Assert.AreEqual(2, searches2.TotalHits); + Assert.AreEqual("zèbre or panthère", this.StipEllipses(searches2.Results[0].Snippet).Trim()); + Assert.AreEqual("zebre without accent", this.StipEllipses(searches2.Results[1].Snippet).Trim()); + } + + [Test] + public void SearchController_PorterFilterTest() + { + // Arrange + string[] lines = + { + "field1_value", + "field2_value", + }; + + this.AddLinesAsSearchDocs(lines); + + // Act + var search1 = this.SearchForKeyword(lines[0]); + var search2 = this.SearchForKeyword("\"" + lines[1] + "\""); + + // Assert + Assert.AreEqual(1, search1.TotalHits); + Assert.AreEqual(1, search2.TotalHits); + + Assert.AreEqual("" + lines[0] + "", this.StipEllipses(search1.Results[0].Snippet).Trim()); + Assert.AreEqual("" + lines[1] + "", this.StipEllipses(search2.Results[0].Snippet).Trim()); + } + + [Test] + public void SearchController_SearchFindsStemmedWords() + { + // Arrange + string[] lines = + { + "I ride my bike to work", + "All team are riding their bikes", + "The boy rides his bike to school", + "This sentence is missing the bike ri... word", + }; + + this.AddLinesAsSearchDocs(lines); + + // Act + var search = this.SearchForKeyword("ride"); + + // Assert + Assert.AreEqual(3, search.TotalHits); + Assert.AreEqual("I ride my bike to work", this.StipEllipses(search.Results[0].Snippet)); + Assert.AreEqual("m are riding their bikes", this.StipEllipses(search.Results[1].Snippet)); + Assert.AreEqual("e boy rides his bike to school", this.StipEllipses(search.Results[2].Snippet)); + } + + [Test] + public void SearchController_Search_Synonym_Works() + { + // Arrange + var added = this.AddStandardSearchDocs(); + + // Act + var search = this.SearchForKeywordInModule("wolf"); + + // Assert + Assert.AreEqual(added, search.TotalHits); + + var snippets = search.Results.Select(result => this.StipEllipses(result.Snippet)).OrderBy(s => s).ToArray(); + Assert.AreEqual("brown fox jumps over the lazy dog", snippets[0]); + Assert.AreEqual("e red fox jumped over the lazy dark gray dog", snippets[1]); + Assert.AreEqual("gold fox jumped over the lazy black dog", snippets[2]); + Assert.AreEqual("quick fox jumps over the black dog - Italian", snippets[3]); + } + + [Test] + public void SearchController_Title_Ranked_Higher_Than_Body() + { + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "Hello World" }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "cow is gone" }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(doc3); + this.internalSearchController.Commit(); + + var result = this.SearchForKeyword("cow"); + + // Assert + Assert.AreEqual(result.TotalHits, 2); + Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); + Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); + } + + [Test] + public void SearchController_Title_Ranked_Higher_Than_Body_Regardless_Of_Document_Sequence() + { + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "cow is gone" }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(doc3); + this.internalSearchController.Commit(); + + var result = this.SearchForKeyword("cow"); + + // Assert + Assert.AreEqual(result.TotalHits, 2); + Assert.AreEqual(doc3.UniqueKey, result.Results[0].UniqueKey); + Assert.AreEqual(doc1.UniqueKey, result.Results[1].UniqueKey); + } + + [Test] + public void SearchController_Title_Ranked_Higher_Than_Tag() + { + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "Hello World" }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { "cow", "hello", "world" } }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(doc3); + this.internalSearchController.Commit(); + var result = this.SearchForKeyword("cow"); + + // Assert + Assert.AreEqual(result.TotalHits, 2); + Console.WriteLine("first score: {0} {1}", result.Results[0].UniqueKey, result.Results[0].DisplayScore); + Console.WriteLine("second score: {0} {1}", result.Results[1].UniqueKey, result.Results[1].DisplayScore); + Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); + Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); + } + + [Test] + public void SearchController_RankingTest_With_Vowel() + { + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "tootsie", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { "tootsie" } }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Keywords = new Dictionary() { { KeyWord1Name, "tootsie" } } }; + var doc4 = new SearchDocument { UniqueKey = "key04", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Description = "tootsie" }; + var doc5 = new SearchDocument { UniqueKey = "key05", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "hello tootsie" }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(doc3); + this.internalSearchController.AddSearchDocument(doc4); + this.internalSearchController.AddSearchDocument(doc5); + + this.internalSearchController.Commit(); + + var result = this.SearchForKeyword("tootsie"); + + // Assert + Assert.AreEqual(5, result.TotalHits); + foreach (var searchResult in result.Results) + { + Console.WriteLine("{0} score: {1}", searchResult.UniqueKey, searchResult.DisplayScore); + } + + Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); + Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); + Assert.AreEqual(doc3.UniqueKey, result.Results[2].UniqueKey); + Assert.AreEqual(doc4.UniqueKey, result.Results[3].UniqueKey); + } + + [Test] + public void SearchController_FileNameTest_With_WildCard() + { + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + + this.internalSearchController.Commit(); + + var result = this.SearchForKeywordWithWildCard("file"); + + // Assert + Assert.AreEqual(1, result.TotalHits); + Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); + } + + [Test] + public void SearchController_Full_FileNameTest_Without_WildCard() + { + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + + this.internalSearchController.Commit(); + + var result = this.SearchForKeywordWithWildCard("file.ext"); + + // Assert + Assert.AreEqual(1, result.TotalHits); + Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); + } + + [Test] + public void SearchController_Full_FileNameTest_With_WildCard() + { + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + + this.internalSearchController.Commit(); + + var result = this.SearchForKeyword("file.ext"); + + // Assert + Assert.AreEqual(1, result.TotalHits); + Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); + } + + [Test] + public void SearchController_Scope_By_FolderName() + { + // Arrange + this.AddFoldersAndFiles(); + + // Act + var result1 = this.SearchForKeyword("kw-folderName:Images/*"); + var result2 = this.SearchForKeyword("kw-folderName:Images/DNN/*"); + var result3 = this.SearchForKeywordWithWildCard("kw-folderName:Images/* AND spacer"); + + // Assert + Assert.AreEqual(5, result1.TotalHits); + Assert.AreEqual(2, result2.TotalHits); + Assert.AreEqual(1, result3.TotalHits); + } + + [Test] + public void SearchController_Scope_By_FolderName_With_Spaces() + { + // Arrange + this.AddFoldersAndFiles(); + + // Act - Space is replaced by < + var query1 = new SearchQuery { KeyWords = "kw-folderName:Images/*", SearchTypeIds = new[] { OtherSearchTypeId }, WildCardSearch = false }; + var query2 = new SearchQuery { KeyWords = "kw-folderName:my() { { NumericKey1, NumericValue50 } }, + SearchTypeIds = new List { OtherSearchTypeId }, + WildCardSearch = false, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual(NumericValue50, search.Results[0].NumericKeys[NumericKey1]); + } + + [Test] + public void SearchController_GetResult_Works_With_CustomKeyword_Querirs() + { + this.AddDocumentsWithKeywords(); + + // Act + var query = new SearchQuery + { + CustomKeywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } }, + SearchTypeIds = new List { OtherSearchTypeId }, + WildCardSearch = false, + }; + var search = this.searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual(KeyWord1Value, search.Results[0].Keywords[KeyWord1Name]); + } + + [Test] + public void SearchController_EnableLeadingWildcard_Should_Not_Return_Results_When_Property_Is_False() + { + this.mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("N"); + + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(doc3); + this.internalSearchController.Commit(); + + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, false); + + // Assert + Assert.AreEqual(0, result.TotalHits); + } + + [Test] + public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Property_Is_True() + { + this.mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("N"); + + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(doc3); + this.internalSearchController.Commit(); + + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, true); + + // Assert + Assert.AreEqual(1, result.TotalHits); + Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); + } + + [Test] + public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Property_Is_False_But_Host_Setting_Is_True() + { + this.mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("Y"); + + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + + // Act + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(doc3); + this.internalSearchController.Commit(); + + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, false); + + // Assert + Assert.AreEqual(1, result.TotalHits); + Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); + } + + [Test] + public void SearchController_Search_StopWords_Works() + { + // Arrange + var added = this.AddStandardSearchDocs(); + this.internalSearchController.Commit(); + + // Act + var search = this.SearchForKeywordInModule("the"); + + // Assert + // the word "the" is ignored in all languages except es-ES + Assert.AreEqual(1, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); + + // Act + search = this.SearchForKeywordInModule("over"); + + // Assert + // we won't find "over" in neutral, en-US, and en-CA documents, but will find it in the es-ES and it-IT documents. + Assert.AreEqual(2, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); + + // Act + search = this.SearchForKeywordInModule("los"); + + // Assert + // we won't find "los" in the es-ES document. + Assert.AreEqual(0, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); + } + + /// + /// Executes function proc on a separate thread respecting the given timeout value. + /// + /// + /// The function to execute. + /// The timeout duration. + /// R. + /// From: http://stackoverflow.com/questions/9460661/implementing-regex-timeout-in-net-4. + private static R ExecuteWithTimeout(Func proc, TimeSpan timeout) + { + var r = default(R); // init default return value + Exception ex = null; // records inter-thread exception + + // define a thread to wrap 'proc' + var t = new Thread(() => + { + try + { + r = proc(); + } + catch (Exception e) + { + // this can get set to ThreadAbortException + ex = e; + + Console.WriteLine("Exception hit"); + } + }); + + t.Start(); // start running 'proc' thread wrapper + + // from docs: "The Start method does not return until the new thread has started running." + if (t.Join(timeout) == false) + { + t.Abort(); // die evil thread! + + // Abort raises the ThreadAbortException + int i = 0; + while ((t.Join(1) == false) && (i < 20)) + { + // 20 ms wait possible here + i++; + } + + if (i >= 20) + { + // we didn't abort, might want to log this or take some other action + // this can happen if you are doing something indefinitely hinky in a + // finally block (cause the finally be will executed before the Abort + // completes. + Console.WriteLine("Abort didn't work as expected"); + } + } + + if (ex != null) + { + throw ex; // oops + } + + return r; // ah! + } + + private void CreateNewLuceneControllerInstance(bool reCreate = false) + { + InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); + this.internalSearchController = InternalSearchController.Instance; + this.searchController = new SearchControllerImpl(); + + if (!reCreate) + { + this.DeleteIndexFolder(); + + if (this.luceneController != null) + { + LuceneController.ClearInstance(); + this.luceneController.Dispose(); + } + + this.luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this.luceneController); + } + } + + private void SetupHostController() + { + this.mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); + this.mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this.readerStaleTimeSpan); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchDescriptionBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); + this.mockHostController.As(); + } + + private void SetupLocaleController() + { + this.mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); + this.mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this.mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this.mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this.mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + + this.mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this.mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this.mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this.mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this.mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + } + + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this.mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + DataTableReader searchTypes = null; + this.mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) + .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) + .Returns(() => searchTypes); + + this.mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + } + + private IDataReader GetPortalsCallBack(string culture) + { + return this.GetPortalCallBack(PortalId0, CultureEnUs); + } + + private IDataReader GetPortalCallBack(int portalId, string culture) + { + var table = new DataTable("Portal"); + + var cols = new[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + const int homePage = 1; + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, + "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, + "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", + null, homePage.ToString("D"), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); + + return table.CreateDataReader(); + } + + private void SetupSearchHelper() + { + this.mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); + this.mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.GetSynonymsCallBack); + this.mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); + this.mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); + this.mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); + this.mockSearchHelper.Setup(x => x.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); + this.mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( + new SearchStopWords + { + PortalId = 0, + CultureCode = CultureEsEs, + StopWords = "los,de,el", + }); + this.mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnUs)).Returns( + new SearchStopWords + { + PortalId = 0, + CultureCode = CultureEnUs, + StopWords = "the,over", + }); + this.mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnCa)).Returns( + new SearchStopWords + { + PortalId = 0, + CultureCode = CultureEnCa, + StopWords = "the,over", + }); + + this.mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new SearchHelperImpl().RephraseSearchText); + this.mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); + SearchHelper.SetTestableInstance(this.mockSearchHelper.Object); + } + + private SearchType GetSearchTypeByNameCallback(string searchTypeName) + { + var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; + switch (searchTypeName) + { + case ModuleSearchTypeName: + searchType.SearchTypeId = ModuleSearchTypeId; + break; + case TabSearchTypeName: + searchType.SearchTypeId = TabSearchTypeId; + break; + case OtherSearchTypeName: + searchType.SearchTypeId = OtherSearchTypeId; + break; + case DocumentSearchTypeName: + searchType.SearchTypeId = DocumentSearchTypeId; + break; + case UrlSearchTypeName: + searchType.SearchTypeId = UrlSearchTypeId; + break; + } + + return searchType; + } + + private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) + { + var synonyms = new List(); + if (term == "fox") + { + synonyms.Add("wolf"); + } + + return synonyms; + } + + private UserInfo GetUserByIdCallback(int portalId, int userId) + { + if (portalId == PortalId12 && userId == StandardAuthorId) + { + return new UserInfo { UserID = userId, DisplayName = StandardAuthorDisplayName }; + } + + return null; + } + + private DataTable GetAllSearchTypes() + { + var dtSearchTypes = new DataTable("SearchTypes"); + var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); + dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); + dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); + dtSearchTypes.PrimaryKey = new[] { pkId }; + + // Create default Crawler + dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(DocumentSearchTypeId, DocumentSearchTypeName, NoPermissionFakeResultControllerClass); + dtSearchTypes.Rows.Add(UrlSearchTypeId, UrlSearchTypeName, FakeResultControllerClass); + + return dtSearchTypes; + } + + private IEnumerable GetSearchTypes() + { + var searchTypes = new List + { + new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = DocumentSearchTypeId, SearchTypeName = DocumentSearchTypeName, SearchResultClass = NoPermissionFakeResultControllerClass }, + new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, + }; + + return searchTypes; + } + + private void DeleteIndexFolder() + { + try + { + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + } + + /// + /// Returns few SearchDocs. + /// + private IEnumerable GetStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) + { + var searchDocs = new List + { + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag0, Tag1, TagOldest, Tag0WithSpace }, Title = Line1 }, + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag1, Tag2, TagNeutral }, Title = Line2, CultureCode = CultureEnUs }, + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line3, CultureCode = CultureItIt }, + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag3, Tag4, TagLatest }, Title = Line4, CultureCode = CultureEnCa }, + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line5, CultureCode = CultureEsEs }, + }; + + var now = DateTime.UtcNow.AddYears(-searchDocs.Count); + var i = 0; + + foreach (var searchDocument in searchDocs) + { + searchDocument.SearchTypeId = searchTypeId; + searchDocument.UniqueKey = Guid.NewGuid().ToString(); + searchDocument.ModuleId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleId : -1; + searchDocument.ModuleDefId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleDefId : -1; + searchDocument.ModifiedTimeUtc = now.AddYears(++i); // last added is the newest + } + + return searchDocs; + } + + private IEnumerable GetSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) + { + var searchDocs = new List + { + new SearchDocument { PortalId = PortalId0, Title = Line1, Keywords = { { "title", "Hello" } }, Body = "Hello1 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line2, Keywords = { { "subject", "Hello" } }, Body = "Hello2 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line3, Keywords = { { "comments", "Hello" } }, Body = "Hello3 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line4, Keywords = { { "authorname", "Hello" } }, Body = "Hello4 World" }, + }; + + var now = DateTime.UtcNow.AddYears(-searchDocs.Count); + var i = 0; + + foreach (var searchDocument in searchDocs) + { + searchDocument.SearchTypeId = searchTypeId; + searchDocument.UniqueKey = Guid.NewGuid().ToString(); + searchDocument.ModuleId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleId : -1; + searchDocument.ModuleDefId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleDefId : -1; + searchDocument.ModifiedTimeUtc = now.AddYears(++i); // last added is the newest + } + + return searchDocs; + } + + /// + /// Adds standarad SearchDocs in Lucene Index. + /// + /// Number of dcuments added. + private int AddStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) + { + var docs = this.GetStandardSearchDocs(searchTypeId).ToArray(); + this.internalSearchController.AddSearchDocuments(docs); + return docs.Length; + } + + private int AddSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) + { + var docs = this.GetSearchDocsForCustomBoost(searchTypeId).ToArray(); + this.internalSearchController.AddSearchDocuments(docs); + return docs.Length; + } + + private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) + { + var doc1 = new SearchDocument + { + Title = "Title", + UniqueKey = "key1", + Body = "hello", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue50 } }, + }; + var doc2 = new SearchDocument + { + Title = "Title", + UniqueKey = "key2", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue100 } }, + }; + var doc3 = new SearchDocument + { + Title = "Title", + UniqueKey = "key3", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue200 } }, + }; + var doc4 = new SearchDocument + { + Title = "Title", + UniqueKey = "key4", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue500 } }, + }; + var doc5 = new SearchDocument + { + Title = "Title", + UniqueKey = "key5", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue1000 } }, + }; + + var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; + + this.internalSearchController.AddSearchDocuments(docs); + + return docs.Count; + } + + private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) + { + var doc1 = new SearchDocument + { + Title = "Title", + UniqueKey = "key1", + Body = "hello", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } }, + }; + var doc2 = new SearchDocument + { + Title = "Title", + UniqueKey = "key2", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord2Value } }, + }; + var doc3 = new SearchDocument + { + Title = "Title", + UniqueKey = "key3", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord3Value } }, + }; + var doc4 = new SearchDocument + { + Title = "Title", + UniqueKey = "key4", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord4Value } }, + }; + var doc5 = new SearchDocument + { + Title = "Title", + UniqueKey = "key5", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord5Value } }, + }; + + var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; + + this.internalSearchController.AddSearchDocuments(docs); + + return docs.Count; + } + + private int AddDocuments(IList titles, string body, int searchTypeId = OtherSearchTypeId) + { + var count = 0; + foreach (var doc in titles.Select(title => new SearchDocument + { + Title = title, + UniqueKey = Guid.NewGuid().ToString(), + Body = body, + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + })) + { + this.internalSearchController.AddSearchDocument(doc); + count++; + } + + return count; + } + + private int AddDocumentsWithKeywords(IEnumerable keywords, string title, int searchTypeId = OtherSearchTypeId) + { + var count = 0; + foreach (var doc in keywords.Select(keyword => new SearchDocument + { + Title = title, + UniqueKey = Guid.NewGuid().ToString(), + Keywords = new Dictionary() { { KeyWord1Name, keyword } }, + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + })) + { + this.internalSearchController.AddSearchDocument(doc); + count++; + } + + return count; + } + + private void AddLinesAsSearchDocs(IList lines, int searchTypeId = OtherSearchTypeId) + { + var now = DateTime.UtcNow - TimeSpan.FromSeconds(lines.Count()); + var i = 0; + + this.internalSearchController.AddSearchDocuments( + lines.Select(line => + new SearchDocument + { + Title = line, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = searchTypeId, + ModifiedTimeUtc = now.AddSeconds(i++), + }).ToList()); + } + + private SearchResults SearchForKeyword(string keyword, int searchTypeId = OtherSearchTypeId, bool useWildcard = false, bool allowLeadingWildcard = false) + { + var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = useWildcard, AllowLeadingWildcard = allowLeadingWildcard }; + return this.searchController.SiteSearch(query); + } + + private SearchResults SearchForKeywordWithWildCard(string keyword, int searchTypeId = OtherSearchTypeId) + { + var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = true }; + return this.searchController.SiteSearch(query); + } + + private SearchResults SearchForKeywordInModule(string keyword, int searchTypeId = ModuleSearchTypeId) + { + var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId } }; + return this.searchController.SiteSearch(query); + } + + private string StipEllipses(string text) + { + return text.Replace("...", string.Empty).Trim(); + } + + /// + /// Sets up some data for testing security trimming. + /// In the tests below, the users will have access to the follwoing documents + /// { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29, ..., etc. } + /// The tests check that pagination qith various page sizes returns the proper groupings. + /// + private void SetupSecurityTrimmingDocs(int totalDocs, int searchType = DocumentSearchTypeId) + { + var docModifyTime = DateTime.UtcNow - TimeSpan.FromSeconds(totalDocs); + for (var i = 0; i < totalDocs; i++) + { + this.internalSearchController.AddSearchDocument(new SearchDocument + { + AuthorUserId = i, + Title = "Fox and Dog", + Body = Line1, + Tags = new[] { Tag0, Tag1 }, + SearchTypeId = searchType, + UniqueKey = Guid.NewGuid().ToString(), + ModifiedTimeUtc = docModifyTime.AddSeconds(i), + }); + } + } + + private void AddFoldersAndFiles() + { + var allFiles = new Dictionary + { + { "Awesome-Cycles-Logo.png", "Images/" }, + { "Banner1.jpg", "Images/" }, + { "Banner2.jpg", "Images/" }, + { "bike-powered.png", "Images/DNN/" }, + { "Spacer.gif", "Images/DNN/" }, + { "monday.png", "My { { "folderName", file.Value.ToLowerInvariant() } }, + }; + this.internalSearchController.AddSearchDocument(doc); + } + + this.internalSearchController.Commit(); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs index 65d0ba2247a..d68bc794382 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs @@ -2,411 +2,414 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Controllers.Search -{ - using System; - using System.Data; +namespace DotNetNuke.Tests.Core.Controllers.Search +{ + using System; + using System.Data; using System.Linq; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.ComponentModel; - using DotNetNuke.Data; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Search.Internals; using DotNetNuke.Tests.Utilities.Mocks; using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using NUnit.Framework; - - /// - /// Testing various aspects of SearchController. - /// - [TestFixture] - public class SearchHelperTests - { - private const int OtherSearchTypeId = 2; - private const string TermDNN = "DNN"; - private const string TermDotNetNuke = "DotnetNuke"; - private const string TermLaptop = "Laptop"; - private const string TermNotebook = "Notebook"; - private const string TermJump = "Jump"; - private const string TermLeap = "Leap"; - private const string TermHop = "Hop"; - private const int PortalId0 = 0; - private const string CultureEnUs = "en-US"; - private Mock _dataProvider; - private Mock _cachingProvider; - private SearchHelperImpl _searchHelper; - - [SetUp] - public void SetUp() - { - var serviceCollection = new ServiceCollection(); + + using Moq; + + using NUnit.Framework; + + /// + /// Testing various aspects of SearchController. + /// + [TestFixture] + public class SearchHelperTests + { + private const int OtherSearchTypeId = 2; + private const string TermDNN = "DNN"; + private const string TermDotNetNuke = "DotnetNuke"; + private const string TermLaptop = "Laptop"; + private const string TermNotebook = "Notebook"; + private const string TermJump = "Jump"; + private const string TermLeap = "Leap"; + private const string TermHop = "Hop"; + private const int PortalId0 = 0; + private const string CultureEnUs = "en-US"; + private Mock _dataProvider; + private Mock _cachingProvider; + private SearchHelperImpl _searchHelper; + + [SetUp] + public void SetUp() + { + var serviceCollection = new ServiceCollection(); var mockApplicationStatusInfo = new Mock(); mockApplicationStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.Install); serviceCollection.AddTransient(container => Mock.Of()); serviceCollection.AddTransient(container => mockApplicationStatusInfo.Object); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - ComponentFactory.Container = new SimpleContainer(); - this._cachingProvider = MockComponentProvider.CreateDataCacheProvider(); - this._dataProvider = MockComponentProvider.CreateDataProvider(); - this.SetupDataProvider(); - this._searchHelper = new SearchHelperImpl(); - DataCache.ClearCache(); - } - - [TearDown] + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + ComponentFactory.Container = new SimpleContainer(); + this._cachingProvider = MockComponentProvider.CreateDataCacheProvider(); + this._dataProvider = MockComponentProvider.CreateDataProvider(); + this.SetupDataProvider(); + this._searchHelper = new SearchHelperImpl(); + DataCache.ClearCache(); + } + + [TearDown] public void TearDown() { Globals.DependencyProvider = null; - } - - [Test] - public void SearchHelper_GetSynonyms_Two_Terms_Returns_Correct_Results() - { - // Arrange - - // Act - var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermDNN).ToArray(); - - // Assert - Assert.AreEqual(1, synonyms.Count()); - Assert.AreEqual(TermDotNetNuke.ToLowerInvariant(), synonyms[0]); - } - - [Test] - public void SearchHelper_GetSynonyms_Three_Terms_Returns_Correct_Results() - { - // Arrange - - // Act - var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermHop).ToArray(); - - // Assert - Assert.AreEqual(2, synonyms.Count()); - Assert.AreEqual(TermJump.ToLowerInvariant(), synonyms[0]); - Assert.AreEqual(TermLeap.ToLowerInvariant(), synonyms[1]); - } - - [Test] - public void SearchHelper_Rephrase_NoWildCardButExact_1() - { - // Arrange - const string inPhrase = "\"brown fox\""; - const string expected = inPhrase; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_NoWildCardButExact_2() - { - // Arrange - const string inPhrase = "\"brown fox\" -\"(Lazy) dog\" jumps"; - const string expected = inPhrase; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_NoWildCardNoExact() - { - // Arrange - const string inPhrase = "(brown) OR (fox AND dog) +jumbs"; - const string expected = inPhrase; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_0() - { - // Arrange - const string inPhrase = "fox dog"; - const string expected = "(fox OR fox*) (dog OR dog*)"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_1() - { - // Arrange - const string inPhrase = "(lazy-dog)"; - const string expected = "(lazy-dog OR lazy-dog*)"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_2() - { - // Arrange - const string inPhrase = "fox (dog)"; - const string expected = "(fox OR fox*) (dog OR dog*)"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_3() - { - // Arrange - const string inPhrase = "(dog) fox"; - const string expected = "(dog OR dog*) (fox OR fox*)"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_4() - { - // Arrange - const string inPhrase = "brown fox (lazy) dog"; - const string expected = "(brown OR brown*) (fox OR fox*) (lazy OR lazy*) (dog OR dog*)"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_5() - { - // Arrange - const string inPhrase = "(brown fox) lazy dog"; - const string expected = "((brown OR brown*) (fox OR fox*)) (lazy OR lazy*) (dog OR dog*)"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_6() - { - // Arrange - const string inPhrase = "brown fox (lazy dog)"; - const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) (dog OR dog*))"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_7() - { - // Arrange - const string inPhrase = "brown fox (lazy AND dog)"; - const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) AND (dog OR dog*))"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardNoExact_8() - { - // Arrange - const string inPhrase = "brown fox (lazy and dog)"; - const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) (and OR and*) (dog OR dog*))"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardWithExact_1() - { - // Arrange - const string inPhrase = "\"brown fox\""; - const string expected = inPhrase; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardWithExact_2() - { - // Arrange - const string inPhrase = "\"brown fox\" dog"; - const string expected = "\"brown fox\" (dog OR dog*)"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardWithExact_3() - { - // Arrange - const string inPhrase = "The +\"brown fox\" -\"Lazy dog\" jumps"; - const string expected = "(The OR The*) +\"brown fox\" -\"Lazy dog\" (jumps OR jumps*)"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - public void SearchHelper_Rephrase_WildCardWithTilde_4() - { - // Arrange - const string inPhrase = "dog jump~2"; - const string expected = "(dog OR dog*) jump~2"; - - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - [Test] - - // Arrange - [TestCase("Cäu", "(Cau OR Cau*)")] - [TestCase("Cäutätörül", "(Cautatorul OR Cautatorul*)")] - [TestCase("Ãbcdef", "(Abcdef OR Abcdef*)")] - public void SearchHelper_Rephrase_AccentedCharsReplaced_Replaced(string inPhrase, string expected) - { - // Act - var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - - // Assert - Assert.AreEqual(expected, analyzed); - } - - private void SetupDataProvider() - { - // Standard DataProvider Path for Logging - this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - - this._dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); - - this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this.GetPortalSettingsCallBack); - - var dataTable = new DataTable("SynonymsGroups"); - var pkId = dataTable.Columns.Add("SynonymsGroupID", typeof(int)); - dataTable.Columns.Add("SynonymsTags", typeof(string)); - dataTable.Columns.Add("CreatedByUserID", typeof(int)); - dataTable.Columns.Add("CreatedOnDate", typeof(DateTime)); - dataTable.Columns.Add("LastModifiedByUserID", typeof(int)); - dataTable.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - dataTable.Columns.Add("PortalID", typeof(int)); - - dataTable.PrimaryKey = new[] { pkId }; - - // Create some test data - var now = DateTime.Now; - dataTable.Rows.Add(1, string.Join(",", new[] { TermDNN, TermDotNetNuke }), 1, now, 1, now, 0); - dataTable.Rows.Add(2, string.Join(",", new[] { TermLaptop, TermNotebook }), 1, now, 1, now, 0); - dataTable.Rows.Add(3, string.Join(",", new[] { TermJump, TermLeap, TermHop }), 1, now, 1, now, 0); - - this._dataProvider.Setup(x => x.GetAllSynonymsGroups(0, It.IsAny())).Returns(dataTable.CreateDataReader()); - } - - private IDataReader GetPortalSettingsCallBack(int portalId, string culture) - { - var table = new DataTable("PortalSettings"); - - var cols = new string[] - { - "SettingName", "SettingValue", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - table.Rows.Add("SearchAdminInitialization", "true", "-1", DateTime.Now, "-1", DateTime.Now, CultureEnUs); - - return table.CreateDataReader(); - } - - private IDataReader GetPortalsCallBack(string culture) - { - return this.GetPortalCallBack(PortalId0, CultureEnUs); - } - - private IDataReader GetPortalCallBack(int portalId, string culture) - { - DataTable table = new DataTable("Portal"); - - var cols = new string[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - var homePage = 1; - table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); - - return table.CreateDataReader(); - } - } -} + } + + [Test] + public void SearchHelper_GetSynonyms_Two_Terms_Returns_Correct_Results() + { + // Arrange + + // Act + var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermDNN).ToArray(); + + // Assert + Assert.AreEqual(1, synonyms.Count()); + Assert.AreEqual(TermDotNetNuke.ToLowerInvariant(), synonyms[0]); + } + + [Test] + public void SearchHelper_GetSynonyms_Three_Terms_Returns_Correct_Results() + { + // Arrange + + // Act + var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermHop).ToArray(); + + // Assert + Assert.AreEqual(2, synonyms.Count()); + Assert.AreEqual(TermJump.ToLowerInvariant(), synonyms[0]); + Assert.AreEqual(TermLeap.ToLowerInvariant(), synonyms[1]); + } + + [Test] + public void SearchHelper_Rephrase_NoWildCardButExact_1() + { + // Arrange + const string inPhrase = "\"brown fox\""; + const string expected = inPhrase; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_NoWildCardButExact_2() + { + // Arrange + const string inPhrase = "\"brown fox\" -\"(Lazy) dog\" jumps"; + const string expected = inPhrase; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_NoWildCardNoExact() + { + // Arrange + const string inPhrase = "(brown) OR (fox AND dog) +jumbs"; + const string expected = inPhrase; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_0() + { + // Arrange + const string inPhrase = "fox dog"; + const string expected = "(fox OR fox*) (dog OR dog*)"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_1() + { + // Arrange + const string inPhrase = "(lazy-dog)"; + const string expected = "(lazy-dog OR lazy-dog*)"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_2() + { + // Arrange + const string inPhrase = "fox (dog)"; + const string expected = "(fox OR fox*) (dog OR dog*)"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_3() + { + // Arrange + const string inPhrase = "(dog) fox"; + const string expected = "(dog OR dog*) (fox OR fox*)"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_4() + { + // Arrange + const string inPhrase = "brown fox (lazy) dog"; + const string expected = "(brown OR brown*) (fox OR fox*) (lazy OR lazy*) (dog OR dog*)"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_5() + { + // Arrange + const string inPhrase = "(brown fox) lazy dog"; + const string expected = "((brown OR brown*) (fox OR fox*)) (lazy OR lazy*) (dog OR dog*)"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_6() + { + // Arrange + const string inPhrase = "brown fox (lazy dog)"; + const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) (dog OR dog*))"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_7() + { + // Arrange + const string inPhrase = "brown fox (lazy AND dog)"; + const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) AND (dog OR dog*))"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardNoExact_8() + { + // Arrange + const string inPhrase = "brown fox (lazy and dog)"; + const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) (and OR and*) (dog OR dog*))"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardWithExact_1() + { + // Arrange + const string inPhrase = "\"brown fox\""; + const string expected = inPhrase; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardWithExact_2() + { + // Arrange + const string inPhrase = "\"brown fox\" dog"; + const string expected = "\"brown fox\" (dog OR dog*)"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardWithExact_3() + { + // Arrange + const string inPhrase = "The +\"brown fox\" -\"Lazy dog\" jumps"; + const string expected = "(The OR The*) +\"brown fox\" -\"Lazy dog\" (jumps OR jumps*)"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + public void SearchHelper_Rephrase_WildCardWithTilde_4() + { + // Arrange + const string inPhrase = "dog jump~2"; + const string expected = "(dog OR dog*) jump~2"; + + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + [Test] + + // Arrange + [TestCase("Cäu", "(Cau OR Cau*)")] + [TestCase("Cäutätörül", "(Cautatorul OR Cautatorul*)")] + [TestCase("Ãbcdef", "(Abcdef OR Abcdef*)")] + public void SearchHelper_Rephrase_AccentedCharsReplaced_Replaced(string inPhrase, string expected) + { + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); + + // Assert + Assert.AreEqual(expected, analyzed); + } + + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + this._dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + + this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this.GetPortalSettingsCallBack); + + var dataTable = new DataTable("SynonymsGroups"); + var pkId = dataTable.Columns.Add("SynonymsGroupID", typeof(int)); + dataTable.Columns.Add("SynonymsTags", typeof(string)); + dataTable.Columns.Add("CreatedByUserID", typeof(int)); + dataTable.Columns.Add("CreatedOnDate", typeof(DateTime)); + dataTable.Columns.Add("LastModifiedByUserID", typeof(int)); + dataTable.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + dataTable.Columns.Add("PortalID", typeof(int)); + + dataTable.PrimaryKey = new[] { pkId }; + + // Create some test data + var now = DateTime.Now; + dataTable.Rows.Add(1, string.Join(",", new[] { TermDNN, TermDotNetNuke }), 1, now, 1, now, 0); + dataTable.Rows.Add(2, string.Join(",", new[] { TermLaptop, TermNotebook }), 1, now, 1, now, 0); + dataTable.Rows.Add(3, string.Join(",", new[] { TermJump, TermLeap, TermHop }), 1, now, 1, now, 0); + + this._dataProvider.Setup(x => x.GetAllSynonymsGroups(0, It.IsAny())).Returns(dataTable.CreateDataReader()); + } + + private IDataReader GetPortalSettingsCallBack(int portalId, string culture) + { + var table = new DataTable("PortalSettings"); + + var cols = new string[] + { + "SettingName", "SettingValue", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + table.Rows.Add("SearchAdminInitialization", "true", "-1", DateTime.Now, "-1", DateTime.Now, CultureEnUs); + + return table.CreateDataReader(); + } + + private IDataReader GetPortalsCallBack(string culture) + { + return this.GetPortalCallBack(PortalId0, CultureEnUs); + } + + private IDataReader GetPortalCallBack(int portalId, string culture) + { + DataTable table = new DataTable("Portal"); + + var cols = new string[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + var homePage = 1; + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); + + return table.CreateDataReader(); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs index 1cedf9e940f..988127da998 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs @@ -2,1278 +2,1280 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Controllers.Social -{ - using System; - using System.Collections.Generic; +namespace DotNetNuke.Tests.Core.Controllers.Social +{ + using System; + using System.Collections.Generic; using System.Data; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.ComponentModel; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Users; - using DotNetNuke.Entities.Users.Social; - using DotNetNuke.Entities.Users.Social.Data; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.Log.EventLog; - using DotNetNuke.Tests.Utilities; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Entities.Users.Social.Data; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Tests.Utilities; using DotNetNuke.Tests.Utilities.Mocks; using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using NUnit.Framework; - - /// - /// Testing various aspects of RelationshipController. - /// - [TestFixture] - public class RelationshipControllerTests - { - private Mock mockCachingProvider; - private Mock _portalController; - private Mock _portalGroupController; - - private DataTable dtRelationshipTypes; - private DataTable dtRelationships; - private DataTable dtUserRelationships; - private DataTable dtUserRelationshipPreferences; - - [SetUp] - public void SetUp() - { - var serviceCollection = new ServiceCollection(); + + using Moq; + + using NUnit.Framework; + + /// + /// Testing various aspects of RelationshipController. + /// + [TestFixture] + public class RelationshipControllerTests + { + private Mock mockCachingProvider; + private Mock _portalController; + private Mock _portalGroupController; + + private DataTable dtRelationshipTypes; + private DataTable dtRelationships; + private DataTable dtUserRelationships; + private DataTable dtUserRelationshipPreferences; + + [SetUp] + public void SetUp() + { + var serviceCollection = new ServiceCollection(); var mockApplicationStatusInfo = new Mock(); mockApplicationStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.Install); serviceCollection.AddTransient(container => mockApplicationStatusInfo.Object); serviceCollection.AddTransient(container => Mock.Of()); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - ComponentFactory.Container = new SimpleContainer(); - var mockDataProvider = MockComponentProvider.CreateDataProvider(); - mockDataProvider.Setup(dp => dp.GetProviderPath()).Returns(string.Empty); - - this.mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - MockComponentProvider.CreateEventLogController(); - - this._portalController = new Mock(); - PortalController.SetTestableInstance(this._portalController.Object); - - this._portalGroupController = new Mock(); - PortalGroupController.RegisterInstance(this._portalGroupController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString("PerformanceSetting")).Returns("0"); - HostController.RegisterInstance(mockHostController.Object); - - var mockUserController = new Mock(); - mockUserController.Setup(c => c.GetCurrentUserInfo()).Returns(new UserInfo() { UserID = 1 }); - UserController.SetTestableInstance(mockUserController.Object); - - this.CreateLocalizationProvider(); - - this.SetupDataTables(); - } - - [TearDown] - public void TearDown() - { - Globals.DependencyProvider = null; - ComponentFactory.Container = null; - PortalController.ClearInstance(); - UserController.ClearInstance(); - } - - [Test] - public void RelationshipController_Constructor_Throws_On_Null_DataService() - { - // Arrange - var mockEventLogController = new Mock(); - - // Act, Assert - Assert.Throws(() => new RelationshipControllerImpl(null, mockEventLogController.Object)); - } - - [Test] - public void RelationshipController_Constructor_Throws_On_Null_EventLogController() - { - // Arrange - var mockDataService = new Mock(); - - // Act, Assert - Assert.Throws(() => new RelationshipControllerImpl(mockDataService.Object, null)); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RelationshipController_DeleteRelationshipType_Throws_On_Null_RelationshipType() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - - // Act, Assert - relationshipController.DeleteRelationshipType(null); - } - - [Test] - public void RelationshipController_DeleteRelationshipType_Calls_DataService() - { - // Arrange - var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = this.CreateRelationshipController(mockDataService); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; - - // Act - relationshipController.DeleteRelationshipType(relationshipType); - - // Assert - mockDataService.Verify(d => d.DeleteRelationshipType(Constants.SOCIAL_FollowerRelationshipTypeID)); - } - - [Test] - public void RelationshipController_DeleteRelationshipType_Calls_EventLogController_AddLog() - { - // Arrange - var mockEventLogController = new Mock(); - mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - this.CreateLocalizationProvider(); - var relationshipController = this.CreateRelationshipController(mockEventLogController); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - Name = Constants.SOCIAL_RelationshipTypeName, - }; - - // Act - relationshipController.DeleteRelationshipType(relationshipType); - - // Assert - var logContent = string.Format(Constants.LOCALIZATION_RelationshipType_Deleted, Constants.SOCIAL_RelationshipTypeName, Constants.SOCIAL_FollowerRelationshipTypeID); - mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - [Test] - public void RelationshipController_DeleteRelationshipType_Calls_DataCache_RemoveCache() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; - - // Act - relationshipController.DeleteRelationshipType(relationshipType); - - // Assert - this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); - } - - [Test] - public void RelationshipController_GetAllRelationshipTypes_Calls_DataService() - { - // Arrange - var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var relationshipTypes = relationshipController.GetAllRelationshipTypes(); - - // Assert - mockDataService.Verify(d => d.GetAllRelationshipTypes()); - } - - [Test] - public void RelationshipController_GetRelationshipType_Calls_DataService_If_Not_Cached() - { - // Arrange - var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var relationshipTypes = relationshipController.GetRelationshipType(Constants.SOCIAL_FriendRelationshipTypeID); - - // Assert - mockDataService.Verify(d => d.GetAllRelationshipTypes()); - } - - [Test] - [TestCase(Constants.SOCIAL_FriendRelationshipTypeID)] - [TestCase(Constants.SOCIAL_FollowerRelationshipTypeID)] - public void RelationshipController_GetRelationshipType_Returns_RelationshipType_For_Valid_ID(int relationshipTypeId) - { - // Arrange - var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var relationshipType = relationshipController.GetRelationshipType(relationshipTypeId); - - // Assert - Assert.AreEqual(relationshipTypeId, relationshipType.RelationshipTypeId); - } - - [Test] - public void RelationshipController_GetRelationshipType_Returns_Null_For_InValid_ID() - { - // Arrange - var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var relationshipType = relationshipController.GetRelationshipType(Constants.SOCIAL_InValidRelationshipType); - - // Assert - Assert.IsNull(relationshipType); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RelationshipController_SaveRelationshipType_Throws_On_Null_RelationshipType() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - - // Act, Assert - relationshipController.SaveRelationshipType(null); - } - - [Test] - public void RelationshipController_SaveRelationshipType_Calls_DataService() - { - // Arrange - var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = this.CreateRelationshipController(mockDataService); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; - - // Act - relationshipController.SaveRelationshipType(relationshipType); - - // Assert - mockDataService.Verify(d => d.SaveRelationshipType(relationshipType, It.IsAny())); - } - - [Test] - public void RelationshipController_SaveRelationshipType_Calls_EventLogController_AddLog() - { - // Arrange - var mockEventLogController = new Mock(); - mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - this.CreateLocalizationProvider(); - - var relationshipController = this.CreateRelationshipController(mockEventLogController); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - Name = Constants.SOCIAL_RelationshipTypeName, - }; - - // Act - relationshipController.SaveRelationshipType(relationshipType); - - // Assert - var logContent = string.Format(Constants.LOCALIZATION_RelationshipType_Updated, Constants.SOCIAL_RelationshipTypeName); - mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - [Test] - public void RelationshipController_SaveRelationshipType_Calls_DataCache_RemoveCache() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; - - // Act - relationshipController.SaveRelationshipType(relationshipType); - - // Assert - this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RelationshipController_DeleteRelationship_Throws_On_Null_Relationship() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - - // Act, Assert - relationshipController.DeleteRelationship(null); - } - - [Test] - public void RelationshipController_DeleteRelationship_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - var relationshipController = this.CreateRelationshipController(mockDataService); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - }; - - // Act - relationshipController.DeleteRelationship(relationship); - - // Assert - mockDataService.Verify(d => d.DeleteRelationship(Constants.SOCIAL_FollowerRelationshipID)); - } - - [Test] - public void RelationshipController_DeleteRelationship_Calls_EventLogController_AddLog() - { - // Arrange - var mockEventLogController = new Mock(); - mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - this.CreateLocalizationProvider(); - - var relationshipController = this.CreateRelationshipController(mockEventLogController); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - Name = Constants.SOCIAL_RelationshipName, - }; - - // Act - relationshipController.DeleteRelationship(relationship); - - // Assert - var logContent = string.Format(Constants.LOCALIZATION_Relationship_Deleted, Constants.SOCIAL_RelationshipName, Constants.SOCIAL_FollowerRelationshipID); - mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - [Test] - public void RelationshipController_DeleteRelationship_Calls_DataCache_RemoveCache() - { - // Arrange - var portalId = 1; - var relationshipController = this.CreateRelationshipController(); - var cacheKey = CachingProvider.GetCacheKey(string.Format(DataCache.RelationshipByPortalIDCacheKey, portalId)); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - PortalId = portalId, - UserId = -1, - }; - - // Act - relationshipController.DeleteRelationship(relationship); - - // Assert - this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); - } - - [Test] - [TestCase(Constants.SOCIAL_FriendRelationshipID, DefaultRelationshipTypes.Friends)] - [TestCase(Constants.SOCIAL_FollowerRelationshipID, DefaultRelationshipTypes.Followers)] - public void RelationshipController_GetRelationship_Returns_Relationship_For_Valid_ID(int relationshipId, DefaultRelationshipTypes defaultType) - { - // Arrange - var mockDataService = new Mock(); - this.dtRelationships.Clear(); - this.dtRelationships.Rows.Add(relationshipId, defaultType, defaultType.ToString(), defaultType.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); - mockDataService.Setup(md => md.GetRelationship(relationshipId)).Returns(this.dtRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var relationship = relationshipController.GetRelationship(relationshipId); - - // Assert - Assert.AreEqual(relationshipId, relationship.RelationshipId); - } - - [Test] - public void RelationshipController_GetRelationship_Returns_Null_For_InValid_ID() - { - // Arrange - var mockDataService = new Mock(); - this.dtRelationships.Clear(); - mockDataService.Setup(md => md.GetRelationship(It.IsAny())).Returns(this.dtRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var relationship = relationshipController.GetRelationship(Constants.SOCIAL_InValidRelationship); - - // Assert - Assert.IsNull(relationship); - } - - [Test] - public void RelationshipController_GetRelationshipsByUserID_Returns_List_Of_Relationships_For_Valid_User() - { - // Arrange - var mockDataService = new Mock(); - this.dtRelationships.Clear(); - for (int i = 1; i <= 5; i++) - { - this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), - DefaultRelationshipTypes.Friends.ToString(), - Constants.PORTAL_Zero, - Constants.USER_ValidId, - RelationshipStatus.None); - } - - mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_ValidId)).Returns(this.dtRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var relationships = relationshipController.GetRelationshipsByUserId(Constants.USER_ValidId); - - // Assert - Assert.IsInstanceOf>(relationships); - Assert.AreEqual(5, relationships.Count); - } - - [Test] - public void RelationshipController_GetRelationshipsByUserID_Returns_EmptyList_Of_Relationships_For_InValid_User() - { - // Arrange - var mockDataService = new Mock(); - this.dtRelationships.Clear(); - mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_InValidId)).Returns(this.dtRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var relationships = relationshipController.GetRelationshipsByUserId(Constants.USER_InValidId); - - // Assert - Assert.IsInstanceOf>(relationships); - Assert.AreEqual(0, relationships.Count); - } - - [Test] - public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Relationships_For_Valid_Portal() - { - // Arrange - var mockDataService = new Mock(); - this.dtRelationships.Clear(); - for (int i = 1; i <= 5; i++) - { - this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), - DefaultRelationshipTypes.Friends.ToString(), - Constants.PORTAL_Zero, - Constants.USER_Null, - RelationshipStatus.None); - } - - mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(this.dtRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - // Act - var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Zero); - - // Assert - Assert.IsInstanceOf>(relationships); - Assert.AreEqual(5, relationships.Count); - } - - [Test] - public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Relationships_For_Valid_Portal_When_Portal_Is_In_Group() - { - // Arrange - var mockDataService = new Mock(); - this.dtRelationships.Clear(); - for (int i = 1; i <= 5; i++) - { - this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), - DefaultRelationshipTypes.Friends.ToString(), - Constants.PORTAL_Zero, - Constants.USER_Null, - RelationshipStatus.None); - } - - mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(this.dtRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); - this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); - - // Act - var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Zero); - - // Assert - Assert.IsInstanceOf>(relationships); - Assert.AreEqual(5, relationships.Count); - } - - [Test] - public void RelationshipController_GetRelationshipsByPortalID_Returns_EmptyList_Of_Relationships_For_InValid_Portal() - { - // Arrange - var mockDataService = new Mock(); - this.dtRelationships.Clear(); - mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Null)).Returns(this.dtRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Null, Null.NullInteger); - this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Null)).Returns(mockPortalInfo); - - // Act - var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Null); - - // Assert - Assert.IsInstanceOf>(relationships); - Assert.AreEqual(0, relationships.Count); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RelationshipController_SaveRelationship_Throws_On_Null_Relationship() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - - // Act, Assert - relationshipController.SaveRelationship(null); - } - - [Test] - public void RelationshipController_SaveRelationship_Calls_DataService() - { - // Arrange - var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = this.CreateRelationshipController(mockDataService); - var relationship = new Relationship - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - }; - - // Act - relationshipController.SaveRelationship(relationship); - - // Assert - mockDataService.Verify(d => d.SaveRelationship(relationship, It.IsAny())); - } - - [Test] - public void RelationshipController_SaveRelationship_Calls_EventLogController_AddLog() - { - // Arrange - var mockEventLogController = new Mock(); - mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - this.CreateLocalizationProvider(); - - var relationshipController = this.CreateRelationshipController(mockEventLogController); - var relationship = new Relationship - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - Name = Constants.SOCIAL_RelationshipName, - }; - - // Act - relationshipController.SaveRelationship(relationship); - - // Assert - var logContent = string.Format(Constants.LOCALIZATION_Relationship_Updated, Constants.SOCIAL_RelationshipName); - mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - [Test] - public void RelationshipController_SaveRelationship_Calls_DataCache_RemoveCache() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; - - // Act - relationshipController.SaveRelationshipType(relationshipType); - - // Assert - this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RelationshipController_DeleteUserRelationship_Throws_On_Null_UserRelationship() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - - // Act, Assert - relationshipController.DeleteUserRelationship(null); - } - - [Test] - public void RelationshipController_DeleteUserRelationship_Calls_DataService() - { - // Arrange - var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = this.CreateRelationshipController(mockDataService); - var userRelationship = new UserRelationship() - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - }; - - // Act - relationshipController.DeleteUserRelationship(userRelationship); - - // Assert - mockDataService.Verify(d => d.DeleteUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11)); - } - - [Test] - public void RelationshipController_DeleteUserRelationship_Calls_EventLogController_AddLog() - { - // Arrange - var mockEventLogController = new Mock(); - mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - this.CreateLocalizationProvider(); - - var relationshipController = this.CreateRelationshipController(mockEventLogController); - var userRelationship = new UserRelationship - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - UserId = Constants.USER_ElevenId, - RelatedUserId = Constants.USER_TenId, - }; - - // Act - relationshipController.DeleteUserRelationship(userRelationship); - - // Assert - var logContent = string.Format(Constants.LOCALIZATION_UserRelationship_Deleted, Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_ElevenId, Constants.USER_TenId); - mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - [Test] - [TestCase(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId)] - [TestCase(Constants.SOCIAL_UserRelationshipIDUser12User13, 12, 13)] - public void RelationshipController_GetUserRelationship_Returns_Relationship_For_Valid_ID(int userRelationshipId, int userId, int relatedUserId) - { - // Arrange - var mockDataService = new Mock(); - this.dtUserRelationships.Clear(); - this.dtUserRelationships.Rows.Add(userRelationshipId, userId, relatedUserId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); - mockDataService.Setup(md => md.GetUserRelationship(userRelationshipId)).Returns(this.dtUserRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var userRelationship = relationshipController.GetUserRelationship(userRelationshipId); - - // Assert - Assert.AreEqual(userRelationshipId, userRelationship.UserRelationshipId); - } - - [Test] - public void RelationshipController_GetUserRelationship_Returns_Null_For_InValid_ID() - { - // Arrange - var mockDataService = new Mock(); - this.dtUserRelationships.Clear(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var userRelationship = relationshipController.GetUserRelationship(Constants.SOCIAL_InValidUserRelationship); - - // Assert - Assert.IsNull(userRelationship); - } - - [Test] - public void RelationshipController_GetUserRelationships_Returns_List_Of_UserRelationships_For_Valid_User() - { - // Arrange - var mockDataService = new Mock(); - this.dtUserRelationships.Clear(); - for (int i = 1; i <= 5; i++) - { - this.dtUserRelationships.Rows.Add(i, Constants.USER_ValidId, Constants.USER_TenId, - Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); - } - - mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_ValidId)).Returns(this.dtUserRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var user = new UserInfo { UserID = Constants.USER_ValidId }; - var userRelationships = relationshipController.GetUserRelationships(user); - - // Assert - Assert.IsInstanceOf>(userRelationships); - Assert.AreEqual(5, userRelationships.Count); - } - - [Test] - public void RelationshipController_GetUserRelationships_Returns_EmptyList_Of_UserRelationships_For_InValid_User() - { - // Arrange - var mockDataService = new Mock(); - this.dtUserRelationships.Clear(); - - mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_InValidId)).Returns(this.dtUserRelationships.CreateDataReader()); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var user = new UserInfo { UserID = Constants.USER_InValidId }; - var userRelationships = relationshipController.GetUserRelationships(user); - - // Assert - Assert.IsInstanceOf>(userRelationships); - Assert.AreEqual(0, userRelationships.Count); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RelationshipController_SaveUserRelationship_Throws_On_Null_UserRelationship() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - - // Act, Assert - relationshipController.SaveUserRelationship(null); - } - - [Test] - public void RelationshipController_SaveUserRelationship_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - var relationshipController = this.CreateRelationshipController(mockDataService); - var userRelationship = new UserRelationship() - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - }; - - // Act - relationshipController.SaveUserRelationship(userRelationship); - - // Assert - mockDataService.Verify(d => d.SaveUserRelationship(userRelationship, It.IsAny())); - } - - [Test] - public void RelationshipController_SaveUserRelationship_Calls_EventLogController_AddLog() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.SaveUserRelationship(It.IsAny(), It.IsAny())) - .Returns(Constants.SOCIAL_UserRelationshipIDUser10User11); - var mockEventLogController = new Mock(); - mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - this.CreateLocalizationProvider(); - - var relationshipController = new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); - var userRelationship = new UserRelationship - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - UserId = Constants.USER_ElevenId, - RelatedUserId = Constants.USER_TenId, - }; - - // Act - relationshipController.SaveUserRelationship(userRelationship); - - // Assert - var logContent = string.Format(Constants.LOCALIZATION_UserRelationship_Updated, Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_ElevenId, Constants.USER_TenId); - mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RelationshipController_DeleteUserRelationshipPreference_Throws_On_Null_UserRelationshipPreference() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - - // Act, Assert - relationshipController.DeleteUserRelationshipPreference(null); - } - - [Test] - public void RelationshipController_DeleteUserRelationshipPreference_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - var relationshipController = this.CreateRelationshipController(mockDataService); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - }; - - // Act - relationshipController.DeleteUserRelationshipPreference(preference); - - // Assert - mockDataService.Verify(d => d.DeleteUserRelationshipPreference(Constants.SOCIAL_PrefereceIDForUser11)); - } - - [Test] - public void RelationshipController_DeleteUserRelationshipPreference_Calls_EventLogController_AddLog() - { - // Arrange - var mockEventLogController = new Mock(); - mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - this.CreateLocalizationProvider(); - - var relationshipController = this.CreateRelationshipController(mockEventLogController); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID, - }; - - // Act - relationshipController.DeleteUserRelationshipPreference(preference); - - // Assert - var logContent = string.Format(Constants.LOCALIZATION_UserRelationshipPreference_Deleted, Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID); - mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - [Test] - public void RelationshipController_GetUserRelationshipPreference_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetUserRelationshipPreferenceById(It.IsAny())) - .Returns(this.dtUserRelationshipPreferences.CreateDataReader); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var preference = relationshipController.GetUserRelationshipPreference(Constants.SOCIAL_PrefereceIDForUser11); - - // Assert - mockDataService.Verify(d => d.GetUserRelationshipPreferenceById(Constants.SOCIAL_PrefereceIDForUser11)); - } - - [Test] - public void RelationshipController_GetUserRelationshipPreference_Overload_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetUserRelationshipPreference(It.IsAny(), It.IsAny())) - .Returns(this.dtUserRelationshipPreferences.CreateDataReader); - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var preference = relationshipController.GetUserRelationshipPreference(Constants.USER_ValidId, Constants.SOCIAL_FriendRelationshipID); - - // Assert - mockDataService.Verify(d => d.GetUserRelationshipPreference(Constants.USER_ValidId, Constants.SOCIAL_FriendRelationshipID)); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RelationshipController_SaveUserRelationshipPreference_Throws_On_Null_UserRelationshipPreference() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - - // Act, Assert - relationshipController.SaveUserRelationshipPreference(null); - } - - [Test] - public void RelationshipController_SaveUserRelationshipPreference_Calls_DataService() - { - // Arrange - var mockDataService = new Mock(); - var relationshipController = this.CreateRelationshipController(mockDataService); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID, - }; - - // Act - relationshipController.SaveUserRelationshipPreference(preference); - - // Assert - mockDataService.Verify(d => d.SaveUserRelationshipPreference(preference, It.IsAny())); - } - - [Test] - public void RelationshipController_SaveUserRelationshipPreference_Calls_EventLogController_AddLog() - { - // Arrange - var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.SaveUserRelationshipPreference(It.IsAny(), It.IsAny())) - .Returns(Constants.SOCIAL_PrefereceIDForUser11); - var mockEventLogController = new Mock(); - mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - this.CreateLocalizationProvider(); - - var relationshipController = new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID, - }; - - // Act - relationshipController.SaveUserRelationshipPreference(preference); - - // Assert - var logContent = string.Format(Constants.LOCALIZATION_UserRelationshipPreference_Updated, Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID); - mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException))] - public void RelationshipController_InitiateUserRelationship_Throws_On_Negative_RelationshipID() - { - // Arrange - var relationshipController = this.CreateRelationshipController(); - var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; - var relationship = new Relationship(); - - // Act, Assert - relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - } - - [Test] - public void RelationshipController_InitiateUserRelationship_Returns_Status_Accepted_When_Default_Relationship_Action_Is_Accepted() - { - // Arrange - var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; - var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; - - this.dtUserRelationships.Rows.Clear(); - this.dtUserRelationshipPreferences.Rows.Clear(); - - // setup mock DataService - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - - // Assert - Assert.AreEqual(userRelationship.Status, RelationshipStatus.Accepted); - } - - [Test] - public void RelationshipController_InitiateUserRelationship_Returns_Status_Initiated_When_Default_Relationship_Action_Is_None() - { - // Arrange - var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; - var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.None }; - - this.dtUserRelationships.Rows.Clear(); - this.dtUserRelationshipPreferences.Rows.Clear(); - - // setup mock DataService - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - - // Assert - Assert.AreEqual(userRelationship.Status, RelationshipStatus.Pending); - } - - [Test] - public void RelationshipController_InitiateUserRelationship_Returns_Status_Accepted_When_TargetUsers_Relationship_Action_Is_Accepted() - { - // Arrange - var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; - var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; - - this.dtUserRelationships.Rows.Clear(); - this.dtUserRelationshipPreferences.Rows.Clear(); - this.dtUserRelationshipPreferences.Rows.Add(Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_TenId, Constants.USER_ElevenId, RelationshipStatus.Accepted); - - // setup mock DataService - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - - // Assert - Assert.AreEqual(userRelationship.Status, RelationshipStatus.Accepted); - } - - [Test] - public void RelationshipController_InitiateUserRelationship_Returns_Status_Initiated_When_TargetUsers_Relationship_Action_Is_None() - { - // Arrange - var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; - var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; - - this.dtUserRelationships.Rows.Clear(); - this.dtUserRelationshipPreferences.Rows.Clear(); - this.dtUserRelationshipPreferences.Rows.Add(Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_TenId, Constants.USER_ElevenId, RelationshipStatus.None); - - // setup mock DataService - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - - // Assert - Assert.AreEqual(userRelationship.Status, RelationshipStatus.Pending); - } - - [Test] - [ExpectedException(typeof(UserRelationshipDoesNotExistException))] - public void RelationshipController_RemoveUserRelationship_Throws_On_NonExistent_Relationship() - { - // Arrange - - // No UserRelationship between user10 and user11 - this.dtUserRelationships.Rows.Clear(); - - // setup mock DataService - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act, Assert - relationshipController.RemoveUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); - } - - [Test] - [ExpectedException(typeof(UserRelationshipDoesNotExistException))] - public void RelationshipController_AcceptRelationship_Throws_On_NonExistent_Relationship() - { - // Arrange - - // No UserRelationship between user10 and user11 - this.dtUserRelationships.Rows.Clear(); - - // setup mock DataService - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act, Assert - relationshipController.AcceptUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); - } - - [Test] - public void RelationshipController_AcceptUserRelationship_Calls_DataService_On_Valid_RelationshipID() - { - // Arrange - - // Any UserRelationship between user10 and user11 - this.dtUserRelationships.Rows.Clear(); - this.dtUserRelationships.Rows.Add(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); - - // setup mock DataService - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.SaveUserRelationship(It.IsAny(), It.IsAny())); - - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - relationshipController.AcceptUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); - - // Assert - mockDataService.Verify(ds => ds.SaveUserRelationship(It.IsAny(), It.IsAny())); - } - - [Test] - public void RelationshipController_RemoveUserRelationship_Calls_DataService_On_Valid_RelationshipID() - { - // Arrange - - // Any UserRelationship between user10 and user11 - this.dtUserRelationships.Rows.Clear(); - this.dtUserRelationships.Rows.Add(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); - - // setup mock DataService - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.DeleteUserRelationship(It.IsAny())); - - var relationshipController = this.CreateRelationshipController(mockDataService); - - // Act - relationshipController.RemoveUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); - - // Assert - mockDataService.Verify(ds => ds.DeleteUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11)); - } - - private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) - { - var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId }; - return mockPortalInfo; - } - - private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int masterPortalId) - { - var mockPortalGroupInfo = new PortalGroupInfo - { - PortalGroupId = portalGroupId, - MasterPortalId = masterPortalId, - PortalGroupName = Constants.PORTALGROUP_ValidName, - PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, - }; - - return mockPortalGroupInfo; - } - - private Mock CreateMockDataServiceWithRelationshipTypes() - { - var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - mockDataService.Setup(md => md.GetRelationshipsByPortalId(It.IsAny())).Returns(this.dtRelationships.CreateDataReader()); - return mockDataService; - } - - private void CreateLocalizationProvider() - { - var mockProvider = MockComponentProvider.CreateLocalizationProvider(); - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_RelationshipType_Deleted_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_RelationshipType_Deleted); - - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_RelationshipType_Updated_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_RelationshipType_Updated); - - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_Relationship_Deleted_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_Relationship_Deleted); - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_Relationship_Updated_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_Relationship_Updated); - - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationshipPreference_Deleted_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_UserRelationshipPreference_Deleted); - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationshipPreference_Updated_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_UserRelationshipPreference_Updated); - - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationship_Deleted_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_UserRelationship_Deleted); - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationship_Added_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_UserRelationship_Added); - mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationship_Updated_Key, It.IsAny())) - .Returns(Constants.LOCALIZATION_UserRelationship_Updated); - } - - private RelationshipControllerImpl CreateRelationshipController() - { - var mockDataService = new Mock(); - return this.CreateRelationshipController(mockDataService); - } - - private RelationshipControllerImpl CreateRelationshipController(Mock mockDataService) - { - var mockEventLogController = new Mock(); - return new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); - } - - private RelationshipControllerImpl CreateRelationshipController(Mock mockEventLogController) - { - var mockDataService = new Mock(); - return new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); - } - - private void SetupDataTables() - { - // RelationshipTypes - this.dtRelationshipTypes = new DataTable("RelationshipTypes"); - var pkRelationshipTypeID = this.dtRelationshipTypes.Columns.Add("RelationshipTypeID", typeof(int)); - this.dtRelationshipTypes.Columns.Add("Name", typeof(string)); - this.dtRelationshipTypes.Columns.Add("Description", typeof(string)); - this.dtRelationshipTypes.Columns.Add("Direction", typeof(int)); - this.dtRelationshipTypes.Columns.Add("CreatedByUserID", typeof(int)); - this.dtRelationshipTypes.Columns.Add("CreatedOnDate", typeof(DateTime)); - this.dtRelationshipTypes.Columns.Add("LastModifiedByUserID", typeof(int)); - this.dtRelationshipTypes.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - this.dtRelationshipTypes.PrimaryKey = new[] { pkRelationshipTypeID }; - - this.dtRelationshipTypes.Rows.Add(DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), DefaultRelationshipTypes.Friends.ToString(), RelationshipDirection.TwoWay); - this.dtRelationshipTypes.Rows.Add(DefaultRelationshipTypes.Followers, DefaultRelationshipTypes.Followers.ToString(), DefaultRelationshipTypes.Followers.ToString(), RelationshipDirection.OneWay); - - // Relationships - this.dtRelationships = new DataTable("Relationships"); - var pkRelationshipID = this.dtRelationships.Columns.Add("RelationshipID", typeof(int)); - this.dtRelationships.Columns.Add("RelationshipTypeID", typeof(int)); - this.dtRelationships.Columns.Add("Name", typeof(string)); - this.dtRelationships.Columns.Add("Description", typeof(string)); - this.dtRelationships.Columns.Add("PortalID", typeof(int)); - this.dtRelationships.Columns.Add("UserID", typeof(int)); - this.dtRelationships.Columns.Add("DefaultResponse", typeof(int)); - this.dtRelationships.Columns.Add("CreatedByUserID", typeof(int)); - this.dtRelationships.Columns.Add("CreatedOnDate", typeof(DateTime)); - this.dtRelationships.Columns.Add("LastModifiedByUserID", typeof(int)); - this.dtRelationships.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - this.dtRelationships.PrimaryKey = new[] { pkRelationshipID }; - - // Create default Friend and Social Relationships - this.dtRelationships.Rows.Add(Constants.SOCIAL_FriendRelationshipID, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), DefaultRelationshipTypes.Friends.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); - this.dtRelationships.Rows.Add(Constants.SOCIAL_FollowerRelationshipID, DefaultRelationshipTypes.Followers, DefaultRelationshipTypes.Followers.ToString(), DefaultRelationshipTypes.Followers.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); - - // UserRelationships - this.dtUserRelationships = new DataTable("UserRelationships"); - var pkUserRelationshipID = this.dtUserRelationships.Columns.Add("UserRelationshipID", typeof(int)); - this.dtUserRelationships.Columns.Add("UserID", typeof(int)); - this.dtUserRelationships.Columns.Add("RelatedUserID", typeof(int)); - this.dtUserRelationships.Columns.Add("RelationshipID", typeof(int)); - this.dtUserRelationships.Columns.Add("Status", typeof(int)); - this.dtUserRelationships.Columns.Add("CreatedByUserID", typeof(int)); - this.dtUserRelationships.Columns.Add("CreatedOnDate", typeof(DateTime)); - this.dtUserRelationships.Columns.Add("LastModifiedByUserID", typeof(int)); - this.dtUserRelationships.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - this.dtUserRelationships.PrimaryKey = new[] { pkUserRelationshipID }; - - // UserRelationshipPreferences - this.dtUserRelationshipPreferences = new DataTable("UserRelationshipPreferences"); - var pkPreferenceID = this.dtUserRelationshipPreferences.Columns.Add("PreferenceID", typeof(int)); - this.dtUserRelationshipPreferences.Columns.Add("UserID", typeof(int)); - this.dtUserRelationshipPreferences.Columns.Add("RelationshipID", typeof(int)); - this.dtUserRelationshipPreferences.Columns.Add("DefaultResponse", typeof(int)); - this.dtUserRelationshipPreferences.Columns.Add("CreatedByUserID", typeof(int)); - this.dtUserRelationshipPreferences.Columns.Add("CreatedOnDate", typeof(DateTime)); - this.dtUserRelationshipPreferences.Columns.Add("LastModifiedByUserID", typeof(int)); - this.dtUserRelationshipPreferences.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - this.dtUserRelationshipPreferences.PrimaryKey = new[] { pkPreferenceID }; - } - } + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + ComponentFactory.Container = new SimpleContainer(); + var mockDataProvider = MockComponentProvider.CreateDataProvider(); + mockDataProvider.Setup(dp => dp.GetProviderPath()).Returns(string.Empty); + + this.mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); + MockComponentProvider.CreateEventLogController(); + + this._portalController = new Mock(); + PortalController.SetTestableInstance(this._portalController.Object); + + this._portalGroupController = new Mock(); + PortalGroupController.RegisterInstance(this._portalGroupController.Object); + + var mockHostController = new Mock(); + mockHostController.Setup(c => c.GetString("PerformanceSetting")).Returns("0"); + HostController.RegisterInstance(mockHostController.Object); + + var mockUserController = new Mock(); + mockUserController.Setup(c => c.GetCurrentUserInfo()).Returns(new UserInfo() { UserID = 1 }); + UserController.SetTestableInstance(mockUserController.Object); + + this.CreateLocalizationProvider(); + + this.SetupDataTables(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + ComponentFactory.Container = null; + PortalController.ClearInstance(); + UserController.ClearInstance(); + } + + [Test] + public void RelationshipController_Constructor_Throws_On_Null_DataService() + { + // Arrange + var mockEventLogController = new Mock(); + + // Act, Assert + Assert.Throws(() => new RelationshipControllerImpl(null, mockEventLogController.Object)); + } + + [Test] + public void RelationshipController_Constructor_Throws_On_Null_EventLogController() + { + // Arrange + var mockDataService = new Mock(); + + // Act, Assert + Assert.Throws(() => new RelationshipControllerImpl(mockDataService.Object, null)); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RelationshipController_DeleteRelationshipType_Throws_On_Null_RelationshipType() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + + // Act, Assert + relationshipController.DeleteRelationshipType(null); + } + + [Test] + public void RelationshipController_DeleteRelationshipType_Calls_DataService() + { + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; + + // Act + relationshipController.DeleteRelationshipType(relationshipType); + + // Assert + mockDataService.Verify(d => d.DeleteRelationshipType(Constants.SOCIAL_FollowerRelationshipTypeID)); + } + + [Test] + public void RelationshipController_DeleteRelationshipType_Calls_EventLogController_AddLog() + { + // Arrange + var mockEventLogController = new Mock(); + mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); + this.CreateLocalizationProvider(); + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + Name = Constants.SOCIAL_RelationshipTypeName, + }; + + // Act + relationshipController.DeleteRelationshipType(relationshipType); + + // Assert + var logContent = string.Format(Constants.LOCALIZATION_RelationshipType_Deleted, Constants.SOCIAL_RelationshipTypeName, Constants.SOCIAL_FollowerRelationshipTypeID); + mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); + } + + [Test] + public void RelationshipController_DeleteRelationshipType_Calls_DataCache_RemoveCache() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; + + // Act + relationshipController.DeleteRelationshipType(relationshipType); + + // Assert + this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); + } + + [Test] + public void RelationshipController_GetAllRelationshipTypes_Calls_DataService() + { + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var relationshipTypes = relationshipController.GetAllRelationshipTypes(); + + // Assert + mockDataService.Verify(d => d.GetAllRelationshipTypes()); + } + + [Test] + public void RelationshipController_GetRelationshipType_Calls_DataService_If_Not_Cached() + { + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var relationshipTypes = relationshipController.GetRelationshipType(Constants.SOCIAL_FriendRelationshipTypeID); + + // Assert + mockDataService.Verify(d => d.GetAllRelationshipTypes()); + } + + [Test] + [TestCase(Constants.SOCIAL_FriendRelationshipTypeID)] + [TestCase(Constants.SOCIAL_FollowerRelationshipTypeID)] + public void RelationshipController_GetRelationshipType_Returns_RelationshipType_For_Valid_ID(int relationshipTypeId) + { + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var relationshipType = relationshipController.GetRelationshipType(relationshipTypeId); + + // Assert + Assert.AreEqual(relationshipTypeId, relationshipType.RelationshipTypeId); + } + + [Test] + public void RelationshipController_GetRelationshipType_Returns_Null_For_InValid_ID() + { + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var relationshipType = relationshipController.GetRelationshipType(Constants.SOCIAL_InValidRelationshipType); + + // Assert + Assert.IsNull(relationshipType); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RelationshipController_SaveRelationshipType_Throws_On_Null_RelationshipType() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + + // Act, Assert + relationshipController.SaveRelationshipType(null); + } + + [Test] + public void RelationshipController_SaveRelationshipType_Calls_DataService() + { + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; + + // Act + relationshipController.SaveRelationshipType(relationshipType); + + // Assert + mockDataService.Verify(d => d.SaveRelationshipType(relationshipType, It.IsAny())); + } + + [Test] + public void RelationshipController_SaveRelationshipType_Calls_EventLogController_AddLog() + { + // Arrange + var mockEventLogController = new Mock(); + mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); + this.CreateLocalizationProvider(); + + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + Name = Constants.SOCIAL_RelationshipTypeName, + }; + + // Act + relationshipController.SaveRelationshipType(relationshipType); + + // Assert + var logContent = string.Format(Constants.LOCALIZATION_RelationshipType_Updated, Constants.SOCIAL_RelationshipTypeName); + mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); + } + + [Test] + public void RelationshipController_SaveRelationshipType_Calls_DataCache_RemoveCache() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; + + // Act + relationshipController.SaveRelationshipType(relationshipType); + + // Assert + this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RelationshipController_DeleteRelationship_Throws_On_Null_Relationship() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + + // Act, Assert + relationshipController.DeleteRelationship(null); + } + + [Test] + public void RelationshipController_DeleteRelationship_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + }; + + // Act + relationshipController.DeleteRelationship(relationship); + + // Assert + mockDataService.Verify(d => d.DeleteRelationship(Constants.SOCIAL_FollowerRelationshipID)); + } + + [Test] + public void RelationshipController_DeleteRelationship_Calls_EventLogController_AddLog() + { + // Arrange + var mockEventLogController = new Mock(); + mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); + this.CreateLocalizationProvider(); + + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + Name = Constants.SOCIAL_RelationshipName, + }; + + // Act + relationshipController.DeleteRelationship(relationship); + + // Assert + var logContent = string.Format(Constants.LOCALIZATION_Relationship_Deleted, Constants.SOCIAL_RelationshipName, Constants.SOCIAL_FollowerRelationshipID); + mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); + } + + [Test] + public void RelationshipController_DeleteRelationship_Calls_DataCache_RemoveCache() + { + // Arrange + var portalId = 1; + var relationshipController = this.CreateRelationshipController(); + var cacheKey = CachingProvider.GetCacheKey(string.Format(DataCache.RelationshipByPortalIDCacheKey, portalId)); + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + PortalId = portalId, + UserId = -1, + }; + + // Act + relationshipController.DeleteRelationship(relationship); + + // Assert + this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); + } + + [Test] + [TestCase(Constants.SOCIAL_FriendRelationshipID, DefaultRelationshipTypes.Friends)] + [TestCase(Constants.SOCIAL_FollowerRelationshipID, DefaultRelationshipTypes.Followers)] + public void RelationshipController_GetRelationship_Returns_Relationship_For_Valid_ID(int relationshipId, DefaultRelationshipTypes defaultType) + { + // Arrange + var mockDataService = new Mock(); + this.dtRelationships.Clear(); + this.dtRelationships.Rows.Add(relationshipId, defaultType, defaultType.ToString(), defaultType.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); + mockDataService.Setup(md => md.GetRelationship(relationshipId)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var relationship = relationshipController.GetRelationship(relationshipId); + + // Assert + Assert.AreEqual(relationshipId, relationship.RelationshipId); + } + + [Test] + public void RelationshipController_GetRelationship_Returns_Null_For_InValid_ID() + { + // Arrange + var mockDataService = new Mock(); + this.dtRelationships.Clear(); + mockDataService.Setup(md => md.GetRelationship(It.IsAny())).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var relationship = relationshipController.GetRelationship(Constants.SOCIAL_InValidRelationship); + + // Assert + Assert.IsNull(relationship); + } + + [Test] + public void RelationshipController_GetRelationshipsByUserID_Returns_List_Of_Relationships_For_Valid_User() + { + // Arrange + var mockDataService = new Mock(); + this.dtRelationships.Clear(); + for (int i = 1; i <= 5; i++) + { + this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), + DefaultRelationshipTypes.Friends.ToString(), + Constants.PORTAL_Zero, + Constants.USER_ValidId, + RelationshipStatus.None); + } + + mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_ValidId)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var relationships = relationshipController.GetRelationshipsByUserId(Constants.USER_ValidId); + + // Assert + Assert.IsInstanceOf>(relationships); + Assert.AreEqual(5, relationships.Count); + } + + [Test] + public void RelationshipController_GetRelationshipsByUserID_Returns_EmptyList_Of_Relationships_For_InValid_User() + { + // Arrange + var mockDataService = new Mock(); + this.dtRelationships.Clear(); + mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_InValidId)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var relationships = relationshipController.GetRelationshipsByUserId(Constants.USER_InValidId); + + // Assert + Assert.IsInstanceOf>(relationships); + Assert.AreEqual(0, relationships.Count); + } + + [Test] + public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Relationships_For_Valid_Portal() + { + // Arrange + var mockDataService = new Mock(); + this.dtRelationships.Clear(); + for (int i = 1; i <= 5; i++) + { + this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), + DefaultRelationshipTypes.Friends.ToString(), + Constants.PORTAL_Zero, + Constants.USER_Null, + RelationshipStatus.None); + } + + mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + // Act + var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Zero); + + // Assert + Assert.IsInstanceOf>(relationships); + Assert.AreEqual(5, relationships.Count); + } + + [Test] + public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Relationships_For_Valid_Portal_When_Portal_Is_In_Group() + { + // Arrange + var mockDataService = new Mock(); + this.dtRelationships.Clear(); + for (int i = 1; i <= 5; i++) + { + this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), + DefaultRelationshipTypes.Friends.ToString(), + Constants.PORTAL_Zero, + Constants.USER_Null, + RelationshipStatus.None); + } + + mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); + this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); + + // Act + var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Zero); + + // Assert + Assert.IsInstanceOf>(relationships); + Assert.AreEqual(5, relationships.Count); + } + + [Test] + public void RelationshipController_GetRelationshipsByPortalID_Returns_EmptyList_Of_Relationships_For_InValid_Portal() + { + // Arrange + var mockDataService = new Mock(); + this.dtRelationships.Clear(); + mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Null)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Null, Null.NullInteger); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Null)).Returns(mockPortalInfo); + + // Act + var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Null); + + // Assert + Assert.IsInstanceOf>(relationships); + Assert.AreEqual(0, relationships.Count); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RelationshipController_SaveRelationship_Throws_On_Null_Relationship() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + + // Act, Assert + relationshipController.SaveRelationship(null); + } + + [Test] + public void RelationshipController_SaveRelationship_Calls_DataService() + { + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var relationship = new Relationship + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + }; + + // Act + relationshipController.SaveRelationship(relationship); + + // Assert + mockDataService.Verify(d => d.SaveRelationship(relationship, It.IsAny())); + } + + [Test] + public void RelationshipController_SaveRelationship_Calls_EventLogController_AddLog() + { + // Arrange + var mockEventLogController = new Mock(); + mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); + this.CreateLocalizationProvider(); + + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var relationship = new Relationship + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + Name = Constants.SOCIAL_RelationshipName, + }; + + // Act + relationshipController.SaveRelationship(relationship); + + // Assert + var logContent = string.Format(Constants.LOCALIZATION_Relationship_Updated, Constants.SOCIAL_RelationshipName); + mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); + } + + [Test] + public void RelationshipController_SaveRelationship_Calls_DataCache_RemoveCache() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; + + // Act + relationshipController.SaveRelationshipType(relationshipType); + + // Assert + this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RelationshipController_DeleteUserRelationship_Throws_On_Null_UserRelationship() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + + // Act, Assert + relationshipController.DeleteUserRelationship(null); + } + + [Test] + public void RelationshipController_DeleteUserRelationship_Calls_DataService() + { + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var userRelationship = new UserRelationship() + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + }; + + // Act + relationshipController.DeleteUserRelationship(userRelationship); + + // Assert + mockDataService.Verify(d => d.DeleteUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11)); + } + + [Test] + public void RelationshipController_DeleteUserRelationship_Calls_EventLogController_AddLog() + { + // Arrange + var mockEventLogController = new Mock(); + mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); + this.CreateLocalizationProvider(); + + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var userRelationship = new UserRelationship + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + UserId = Constants.USER_ElevenId, + RelatedUserId = Constants.USER_TenId, + }; + + // Act + relationshipController.DeleteUserRelationship(userRelationship); + + // Assert + var logContent = string.Format(Constants.LOCALIZATION_UserRelationship_Deleted, Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_ElevenId, Constants.USER_TenId); + mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); + } + + [Test] + [TestCase(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId)] + [TestCase(Constants.SOCIAL_UserRelationshipIDUser12User13, 12, 13)] + public void RelationshipController_GetUserRelationship_Returns_Relationship_For_Valid_ID(int userRelationshipId, int userId, int relatedUserId) + { + // Arrange + var mockDataService = new Mock(); + this.dtUserRelationships.Clear(); + this.dtUserRelationships.Rows.Add(userRelationshipId, userId, relatedUserId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); + mockDataService.Setup(md => md.GetUserRelationship(userRelationshipId)).Returns(this.dtUserRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var userRelationship = relationshipController.GetUserRelationship(userRelationshipId); + + // Assert + Assert.AreEqual(userRelationshipId, userRelationship.UserRelationshipId); + } + + [Test] + public void RelationshipController_GetUserRelationship_Returns_Null_For_InValid_ID() + { + // Arrange + var mockDataService = new Mock(); + this.dtUserRelationships.Clear(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var userRelationship = relationshipController.GetUserRelationship(Constants.SOCIAL_InValidUserRelationship); + + // Assert + Assert.IsNull(userRelationship); + } + + [Test] + public void RelationshipController_GetUserRelationships_Returns_List_Of_UserRelationships_For_Valid_User() + { + // Arrange + var mockDataService = new Mock(); + this.dtUserRelationships.Clear(); + for (int i = 1; i <= 5; i++) + { + this.dtUserRelationships.Rows.Add(i, Constants.USER_ValidId, Constants.USER_TenId, + Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); + } + + mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_ValidId)).Returns(this.dtUserRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var user = new UserInfo { UserID = Constants.USER_ValidId }; + var userRelationships = relationshipController.GetUserRelationships(user); + + // Assert + Assert.IsInstanceOf>(userRelationships); + Assert.AreEqual(5, userRelationships.Count); + } + + [Test] + public void RelationshipController_GetUserRelationships_Returns_EmptyList_Of_UserRelationships_For_InValid_User() + { + // Arrange + var mockDataService = new Mock(); + this.dtUserRelationships.Clear(); + + mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_InValidId)).Returns(this.dtUserRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var user = new UserInfo { UserID = Constants.USER_InValidId }; + var userRelationships = relationshipController.GetUserRelationships(user); + + // Assert + Assert.IsInstanceOf>(userRelationships); + Assert.AreEqual(0, userRelationships.Count); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RelationshipController_SaveUserRelationship_Throws_On_Null_UserRelationship() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + + // Act, Assert + relationshipController.SaveUserRelationship(null); + } + + [Test] + public void RelationshipController_SaveUserRelationship_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var userRelationship = new UserRelationship() + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + }; + + // Act + relationshipController.SaveUserRelationship(userRelationship); + + // Assert + mockDataService.Verify(d => d.SaveUserRelationship(userRelationship, It.IsAny())); + } + + [Test] + public void RelationshipController_SaveUserRelationship_Calls_EventLogController_AddLog() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.SaveUserRelationship(It.IsAny(), It.IsAny())) + .Returns(Constants.SOCIAL_UserRelationshipIDUser10User11); + var mockEventLogController = new Mock(); + mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); + this.CreateLocalizationProvider(); + + var relationshipController = new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); + var userRelationship = new UserRelationship + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + UserId = Constants.USER_ElevenId, + RelatedUserId = Constants.USER_TenId, + }; + + // Act + relationshipController.SaveUserRelationship(userRelationship); + + // Assert + var logContent = string.Format(Constants.LOCALIZATION_UserRelationship_Updated, Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_ElevenId, Constants.USER_TenId); + mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RelationshipController_DeleteUserRelationshipPreference_Throws_On_Null_UserRelationshipPreference() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + + // Act, Assert + relationshipController.DeleteUserRelationshipPreference(null); + } + + [Test] + public void RelationshipController_DeleteUserRelationshipPreference_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + }; + + // Act + relationshipController.DeleteUserRelationshipPreference(preference); + + // Assert + mockDataService.Verify(d => d.DeleteUserRelationshipPreference(Constants.SOCIAL_PrefereceIDForUser11)); + } + + [Test] + public void RelationshipController_DeleteUserRelationshipPreference_Calls_EventLogController_AddLog() + { + // Arrange + var mockEventLogController = new Mock(); + mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); + this.CreateLocalizationProvider(); + + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; + + // Act + relationshipController.DeleteUserRelationshipPreference(preference); + + // Assert + var logContent = string.Format(Constants.LOCALIZATION_UserRelationshipPreference_Deleted, Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID); + mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); + } + + [Test] + public void RelationshipController_GetUserRelationshipPreference_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetUserRelationshipPreferenceById(It.IsAny())) + .Returns(this.dtUserRelationshipPreferences.CreateDataReader); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var preference = relationshipController.GetUserRelationshipPreference(Constants.SOCIAL_PrefereceIDForUser11); + + // Assert + mockDataService.Verify(d => d.GetUserRelationshipPreferenceById(Constants.SOCIAL_PrefereceIDForUser11)); + } + + [Test] + public void RelationshipController_GetUserRelationshipPreference_Overload_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.GetUserRelationshipPreference(It.IsAny(), It.IsAny())) + .Returns(this.dtUserRelationshipPreferences.CreateDataReader); + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var preference = relationshipController.GetUserRelationshipPreference(Constants.USER_ValidId, Constants.SOCIAL_FriendRelationshipID); + + // Assert + mockDataService.Verify(d => d.GetUserRelationshipPreference(Constants.USER_ValidId, Constants.SOCIAL_FriendRelationshipID)); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RelationshipController_SaveUserRelationshipPreference_Throws_On_Null_UserRelationshipPreference() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + + // Act, Assert + relationshipController.SaveUserRelationshipPreference(null); + } + + [Test] + public void RelationshipController_SaveUserRelationshipPreference_Calls_DataService() + { + // Arrange + var mockDataService = new Mock(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; + + // Act + relationshipController.SaveUserRelationshipPreference(preference); + + // Assert + mockDataService.Verify(d => d.SaveUserRelationshipPreference(preference, It.IsAny())); + } + + [Test] + public void RelationshipController_SaveUserRelationshipPreference_Calls_EventLogController_AddLog() + { + // Arrange + var mockDataService = new Mock(); + mockDataService.Setup(ds => ds.SaveUserRelationshipPreference(It.IsAny(), It.IsAny())) + .Returns(Constants.SOCIAL_PrefereceIDForUser11); + var mockEventLogController = new Mock(); + mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); + this.CreateLocalizationProvider(); + + var relationshipController = new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; + + // Act + relationshipController.SaveUserRelationshipPreference(preference); + + // Assert + var logContent = string.Format(Constants.LOCALIZATION_UserRelationshipPreference_Updated, Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID); + mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); + } + + [Test] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void RelationshipController_InitiateUserRelationship_Throws_On_Negative_RelationshipID() + { + // Arrange + var relationshipController = this.CreateRelationshipController(); + var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; + var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; + var relationship = new Relationship(); + + // Act, Assert + relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); + } + + [Test] + public void RelationshipController_InitiateUserRelationship_Returns_Status_Accepted_When_Default_Relationship_Action_Is_Accepted() + { + // Arrange + var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; + var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; + var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; + + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Clear(); + + // setup mock DataService + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); + + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); + + // Assert + Assert.AreEqual(userRelationship.Status, RelationshipStatus.Accepted); + } + + [Test] + public void RelationshipController_InitiateUserRelationship_Returns_Status_Initiated_When_Default_Relationship_Action_Is_None() + { + // Arrange + var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; + var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; + var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.None }; + + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Clear(); + + // setup mock DataService + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); + + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); + + // Assert + Assert.AreEqual(userRelationship.Status, RelationshipStatus.Pending); + } + + [Test] + public void RelationshipController_InitiateUserRelationship_Returns_Status_Accepted_When_TargetUsers_Relationship_Action_Is_Accepted() + { + // Arrange + var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; + var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; + var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; + + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Add(Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_TenId, Constants.USER_ElevenId, RelationshipStatus.Accepted); + + // setup mock DataService + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); + + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); + + // Assert + Assert.AreEqual(userRelationship.Status, RelationshipStatus.Accepted); + } + + [Test] + public void RelationshipController_InitiateUserRelationship_Returns_Status_Initiated_When_TargetUsers_Relationship_Action_Is_None() + { + // Arrange + var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; + var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; + var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; + + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Add(Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_TenId, Constants.USER_ElevenId, RelationshipStatus.None); + + // setup mock DataService + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); + + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); + + // Assert + Assert.AreEqual(userRelationship.Status, RelationshipStatus.Pending); + } + + [Test] + [ExpectedException(typeof(UserRelationshipDoesNotExistException))] + public void RelationshipController_RemoveUserRelationship_Throws_On_NonExistent_Relationship() + { + // Arrange + + // No UserRelationship between user10 and user11 + this.dtUserRelationships.Rows.Clear(); + + // setup mock DataService + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act, Assert + relationshipController.RemoveUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); + } + + [Test] + [ExpectedException(typeof(UserRelationshipDoesNotExistException))] + public void RelationshipController_AcceptRelationship_Throws_On_NonExistent_Relationship() + { + // Arrange + + // No UserRelationship between user10 and user11 + this.dtUserRelationships.Rows.Clear(); + + // setup mock DataService + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act, Assert + relationshipController.AcceptUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); + } + + [Test] + public void RelationshipController_AcceptUserRelationship_Calls_DataService_On_Valid_RelationshipID() + { + // Arrange + + // Any UserRelationship between user10 and user11 + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationships.Rows.Add(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); + + // setup mock DataService + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.SaveUserRelationship(It.IsAny(), It.IsAny())); + + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + relationshipController.AcceptUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); + + // Assert + mockDataService.Verify(ds => ds.SaveUserRelationship(It.IsAny(), It.IsAny())); + } + + [Test] + public void RelationshipController_RemoveUserRelationship_Calls_DataService_On_Valid_RelationshipID() + { + // Arrange + + // Any UserRelationship between user10 and user11 + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationships.Rows.Add(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); + + // setup mock DataService + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.DeleteUserRelationship(It.IsAny())); + + var relationshipController = this.CreateRelationshipController(mockDataService); + + // Act + relationshipController.RemoveUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); + + // Assert + mockDataService.Verify(ds => ds.DeleteUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11)); + } + + private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) + { + var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId }; + return mockPortalInfo; + } + + private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int masterPortalId) + { + var mockPortalGroupInfo = new PortalGroupInfo + { + PortalGroupId = portalGroupId, + MasterPortalId = masterPortalId, + PortalGroupName = Constants.PORTALGROUP_ValidName, + PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, + }; + + return mockPortalGroupInfo; + } + + private Mock CreateMockDataServiceWithRelationshipTypes() + { + var mockDataService = new Mock(); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); + mockDataService.Setup(md => md.GetRelationshipsByPortalId(It.IsAny())).Returns(this.dtRelationships.CreateDataReader()); + return mockDataService; + } + + private void CreateLocalizationProvider() + { + var mockProvider = MockComponentProvider.CreateLocalizationProvider(); + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_RelationshipType_Deleted_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_RelationshipType_Deleted); + + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_RelationshipType_Updated_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_RelationshipType_Updated); + + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_Relationship_Deleted_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_Relationship_Deleted); + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_Relationship_Updated_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_Relationship_Updated); + + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationshipPreference_Deleted_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_UserRelationshipPreference_Deleted); + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationshipPreference_Updated_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_UserRelationshipPreference_Updated); + + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationship_Deleted_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_UserRelationship_Deleted); + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationship_Added_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_UserRelationship_Added); + mockProvider.Setup(l => l.GetString(Constants.LOCALIZATION_UserRelationship_Updated_Key, It.IsAny())) + .Returns(Constants.LOCALIZATION_UserRelationship_Updated); + } + + private RelationshipControllerImpl CreateRelationshipController() + { + var mockDataService = new Mock(); + return this.CreateRelationshipController(mockDataService); + } + + private RelationshipControllerImpl CreateRelationshipController(Mock mockDataService) + { + var mockEventLogController = new Mock(); + return new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); + } + + private RelationshipControllerImpl CreateRelationshipController(Mock mockEventLogController) + { + var mockDataService = new Mock(); + return new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); + } + + private void SetupDataTables() + { + // RelationshipTypes + this.dtRelationshipTypes = new DataTable("RelationshipTypes"); + var pkRelationshipTypeID = this.dtRelationshipTypes.Columns.Add("RelationshipTypeID", typeof(int)); + this.dtRelationshipTypes.Columns.Add("Name", typeof(string)); + this.dtRelationshipTypes.Columns.Add("Description", typeof(string)); + this.dtRelationshipTypes.Columns.Add("Direction", typeof(int)); + this.dtRelationshipTypes.Columns.Add("CreatedByUserID", typeof(int)); + this.dtRelationshipTypes.Columns.Add("CreatedOnDate", typeof(DateTime)); + this.dtRelationshipTypes.Columns.Add("LastModifiedByUserID", typeof(int)); + this.dtRelationshipTypes.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + + this.dtRelationshipTypes.PrimaryKey = new[] { pkRelationshipTypeID }; + + this.dtRelationshipTypes.Rows.Add(DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), DefaultRelationshipTypes.Friends.ToString(), RelationshipDirection.TwoWay); + this.dtRelationshipTypes.Rows.Add(DefaultRelationshipTypes.Followers, DefaultRelationshipTypes.Followers.ToString(), DefaultRelationshipTypes.Followers.ToString(), RelationshipDirection.OneWay); + + // Relationships + this.dtRelationships = new DataTable("Relationships"); + var pkRelationshipID = this.dtRelationships.Columns.Add("RelationshipID", typeof(int)); + this.dtRelationships.Columns.Add("RelationshipTypeID", typeof(int)); + this.dtRelationships.Columns.Add("Name", typeof(string)); + this.dtRelationships.Columns.Add("Description", typeof(string)); + this.dtRelationships.Columns.Add("PortalID", typeof(int)); + this.dtRelationships.Columns.Add("UserID", typeof(int)); + this.dtRelationships.Columns.Add("DefaultResponse", typeof(int)); + this.dtRelationships.Columns.Add("CreatedByUserID", typeof(int)); + this.dtRelationships.Columns.Add("CreatedOnDate", typeof(DateTime)); + this.dtRelationships.Columns.Add("LastModifiedByUserID", typeof(int)); + this.dtRelationships.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + this.dtRelationships.PrimaryKey = new[] { pkRelationshipID }; + + // Create default Friend and Social Relationships + this.dtRelationships.Rows.Add(Constants.SOCIAL_FriendRelationshipID, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), DefaultRelationshipTypes.Friends.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); + this.dtRelationships.Rows.Add(Constants.SOCIAL_FollowerRelationshipID, DefaultRelationshipTypes.Followers, DefaultRelationshipTypes.Followers.ToString(), DefaultRelationshipTypes.Followers.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); + + // UserRelationships + this.dtUserRelationships = new DataTable("UserRelationships"); + var pkUserRelationshipID = this.dtUserRelationships.Columns.Add("UserRelationshipID", typeof(int)); + this.dtUserRelationships.Columns.Add("UserID", typeof(int)); + this.dtUserRelationships.Columns.Add("RelatedUserID", typeof(int)); + this.dtUserRelationships.Columns.Add("RelationshipID", typeof(int)); + this.dtUserRelationships.Columns.Add("Status", typeof(int)); + this.dtUserRelationships.Columns.Add("CreatedByUserID", typeof(int)); + this.dtUserRelationships.Columns.Add("CreatedOnDate", typeof(DateTime)); + this.dtUserRelationships.Columns.Add("LastModifiedByUserID", typeof(int)); + this.dtUserRelationships.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + this.dtUserRelationships.PrimaryKey = new[] { pkUserRelationshipID }; + + // UserRelationshipPreferences + this.dtUserRelationshipPreferences = new DataTable("UserRelationshipPreferences"); + var pkPreferenceID = this.dtUserRelationshipPreferences.Columns.Add("PreferenceID", typeof(int)); + this.dtUserRelationshipPreferences.Columns.Add("UserID", typeof(int)); + this.dtUserRelationshipPreferences.Columns.Add("RelationshipID", typeof(int)); + this.dtUserRelationshipPreferences.Columns.Add("DefaultResponse", typeof(int)); + this.dtUserRelationshipPreferences.Columns.Add("CreatedByUserID", typeof(int)); + this.dtUserRelationshipPreferences.Columns.Add("CreatedOnDate", typeof(DateTime)); + this.dtUserRelationshipPreferences.Columns.Add("LastModifiedByUserID", typeof(int)); + this.dtUserRelationshipPreferences.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + this.dtUserRelationshipPreferences.PrimaryKey = new[] { pkPreferenceID }; + } + } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs index fba4752988a..ba0008297b1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs @@ -2,283 +2,305 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Entities.Modules.Settings -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Globalization; - - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Modules.Settings; - using Moq; - using NUnit.Framework; - - [TestFixture] - public class ModuleSettingsTests : BaseSettingsTests - { - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("en-US")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("fr-FR")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("he-IL")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ru-RU")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("tr-TR")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - public void SaveSettings_UpdatesCache() - { - // Arrange - var moduleInfo = GetModuleInfo; - var settings = new ModulesSettings(); - - this.MockModuleSettings(moduleInfo, new Hashtable()); - this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); - var settingsRepository = new ModulesSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - - [Test] - public void GetSettings_CallsGetCachedObject() - { - // Arrange - var moduleInfo = GetModuleInfo; - - this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new ModulesSettings()); - var settingsRepository = new ModulesSettingsRepository(); - - // Act - settingsRepository.GetSettings(moduleInfo); - - // Assert - this.MockRepository.VerifyAll(); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("en-US")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("fr-FR")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("he-IL")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ru-RU")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("tr-TR")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringValue, int integerValue, double doubleValue, - bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - // Arrange - var moduleInfo = GetModuleInfo; - var moduleSettings = new Hashtable - { - { SettingNamePrefix + "StringProperty", stringValue }, - { SettingNamePrefix + "IntegerProperty", integerValue.ToString() }, - { SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "BooleanProperty", booleanValue.ToString() }, - { SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "EnumProperty", enumValue.ToString() }, - { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, - }; - - this.MockModuleSettings(moduleInfo, moduleSettings); - - var settingsRepository = new ModulesSettingsRepository(); - - // Act - var settings = settingsRepository.GetSettings(moduleInfo); - - // Assert - Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); - Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); - Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); - Assert.AreEqual(booleanValue, settings.BooleanProperty, "The retrieved boolean property value is not equal to the stored one"); - Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); - Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); - Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); - Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); - this.MockRepository.VerifyAll(); - } - - private void SaveSettings_CallsUpdateModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, - bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - // Arrange - var moduleInfo = GetModuleInfo; - var settings = new ModulesSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DoubleProperty = doubleValue, - BooleanProperty = booleanValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - EnumProperty = enumValue, - ComplexProperty = complexValue, - }; - - this.MockModuleSettings(moduleInfo, new Hashtable()); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "StringProperty", stringValue)); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); - - var settingsRepository = new ModulesSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - - public class ModulesSettings - { - [ModuleSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = string.Empty; - - [ModuleSetting(Prefix = SettingNamePrefix)] - public int IntegerProperty { get; set; } - - [ModuleSetting(Prefix = SettingNamePrefix)] - public double DoubleProperty { get; set; } - - [ModuleSetting(Prefix = SettingNamePrefix)] - public bool BooleanProperty { get; set; } - - [ModuleSetting(Prefix = SettingNamePrefix)] - public DateTime DateTimeProperty { get; set; } = DateTime.Now; - - [ModuleSetting(Prefix = SettingNamePrefix)] - public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; - - [ModuleSetting(Prefix = SettingNamePrefix)] - public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; - - [ModuleSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] - public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); - } - - public class ModulesSettingsRepository : SettingsRepository - {} - } -} +namespace DotNetNuke.Tests.Core.Entities.Modules.Settings +{ + using System; + using System.Collections; + using System.Globalization; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules.Settings; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class ModuleSettingsTests : BaseSettingsTests + { + [SetUp] + public void Setup() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("en-US")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("fr-FR")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("he-IL")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ru-RU")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("tr-TR")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + public void SaveSettings_UpdatesCache() + { + // Arrange + var moduleInfo = GetModuleInfo; + var settings = new ModulesSettings(); + + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + var settingsRepository = new ModulesSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + [Test] + public void GetSettings_CallsGetCachedObject() + { + // Arrange + var moduleInfo = GetModuleInfo; + + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new ModulesSettings()); + var settingsRepository = new ModulesSettingsRepository(); + + // Act + settingsRepository.GetSettings(moduleInfo); + + // Assert + this.MockRepository.VerifyAll(); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("en-US")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("fr-FR")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("he-IL")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ru-RU")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("tr-TR")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringValue, int integerValue, double doubleValue, + bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + // Arrange + var moduleInfo = GetModuleInfo; + var moduleSettings = new Hashtable + { + { SettingNamePrefix + "StringProperty", stringValue }, + { SettingNamePrefix + "IntegerProperty", integerValue.ToString() }, + { SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "BooleanProperty", booleanValue.ToString() }, + { SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "EnumProperty", enumValue.ToString() }, + { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, + }; + + this.MockModuleSettings(moduleInfo, moduleSettings); + + var settingsRepository = new ModulesSettingsRepository(); + + // Act + var settings = settingsRepository.GetSettings(moduleInfo); + + // Assert + Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); + Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); + Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); + Assert.AreEqual(booleanValue, settings.BooleanProperty, "The retrieved boolean property value is not equal to the stored one"); + Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); + Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); + Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); + Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); + this.MockRepository.VerifyAll(); + } + + private void SaveSettings_CallsUpdateModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, + bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + // Arrange + var moduleInfo = GetModuleInfo; + var settings = new ModulesSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; + + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "StringProperty", stringValue)); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); + + var settingsRepository = new ModulesSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + public class ModulesSettings + { + [ModuleSetting(Prefix = SettingNamePrefix)] + public string StringProperty { get; set; } = string.Empty; + + [ModuleSetting(Prefix = SettingNamePrefix)] + public int IntegerProperty { get; set; } + + [ModuleSetting(Prefix = SettingNamePrefix)] + public double DoubleProperty { get; set; } + + [ModuleSetting(Prefix = SettingNamePrefix)] + public bool BooleanProperty { get; set; } + + [ModuleSetting(Prefix = SettingNamePrefix)] + public DateTime DateTimeProperty { get; set; } = DateTime.Now; + + [ModuleSetting(Prefix = SettingNamePrefix)] + public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; + + [ModuleSetting(Prefix = SettingNamePrefix)] + public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; + + [ModuleSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] + public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); + } + + public class ModulesSettingsRepository : SettingsRepository + {} + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs index 51e46f6689d..dfd8348635d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs @@ -2,264 +2,289 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Entities.Modules.Settings -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Globalization; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Modules.Settings; - using NUnit.Framework; - - [TestFixture] - public class NullableSettingsTests : BaseSettingsTests - { - public readonly object[] NullableCases = - { - new object[] { null, null, null, null, }, - new object[] { string.Empty, -1, DateTime.UtcNow, TimeSpan.FromMilliseconds(3215648), }, - new object[] { "lorem ipsum", 456, DateTime.Now, DateTime.Today - DateTime.Now, }, - }; - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdateSetting_WithRightParameters_ar_JO(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdateSetting_WithRightParameters_ca_ES(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdateSetting_WithRightParameters_zh_CN(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("en-US")] - public void SaveSettings_CallsUpdateSetting_WithRightParameters_en_US(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("fr-FR")] - public void SaveSettings_CallsUpdateSetting_WithRightParameters_fr_FR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("he-IL")] - public void SaveSettings_CallsUpdateSetting_WithRightParameters_he_IL(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("ru-RU")] - public void SaveSettings_CallsUpdateSetting_WithRightParameters_ru_RU(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("tr-TR")] - public void SaveSettings_CallsUpdateSetting_WithRightParameters_tr_TR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - public void SaveSettings_UpdatesCache() - { - // Arrange - var moduleInfo = GetModuleInfo; - var settings = new MyNullableSettings(); - - this.MockModuleSettings(moduleInfo, new Hashtable()); - this.MockTabModuleSettings(moduleInfo, new Hashtable()); - this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); - var settingsRepository = new MyNullableSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - - [Test] - public void GetSettings_CallsGetCachedObject() - { - // Arrange - var moduleInfo = GetModuleInfo; - - this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyNullableSettings()); - var settingsRepository = new MyNullableSettingsRepository(); - - // Act - settingsRepository.GetSettings(moduleInfo); - - // Assert - this.MockRepository.VerifyAll(); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("ar-JO")] - public void GetSettings_GetsValues_FromCorrectSettings_ar_JO(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("ca-ES")] - public void GetSettings_GetsValues_FromCorrectSettings_ca_ES(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("zh-CN")] - public void GetSettings_GetsValues_FromCorrectSettings_zh_CN(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("en-US")] - public void GetSettings_GetsValues_FromCorrectSettings_en_US(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("fr-FR")] - public void GetSettings_GetsValues_FromCorrectSettings_fr_FR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("he-IL")] - public void GetSettings_GetsValues_FromCorrectSettings_he_IL(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("ru-RU")] - public void GetSettings_GetsValues_FromCorrectSettings_ru_RU(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - [Test] - [TestCaseSource(nameof(NullableCases))] - [SetCulture("tr-TR")] - public void GetSettings_GetsValues_FromCorrectSettings_tr_TR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); - } - - private void SaveSettings_CallsUpdateSetting_WithRightParameters(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - // Arrange - var moduleInfo = GetModuleInfo; - var settings = new MyNullableSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - }; - - this.MockModuleSettings(moduleInfo, new Hashtable()); - this.MockTabModuleSettings(moduleInfo, new Hashtable()); - var expectedStringValue = stringValue ?? string.Empty; - this.MockModuleController.Setup(pc => pc.UpdateModuleSetting(ModuleId, "StringProperty", expectedStringValue)); - var integerString = integerValue?.ToString() ?? string.Empty; - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, "IntegerProperty", integerString, true, Null.NullString, false)); - var dateTimeString = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty; - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, "DateTimeProperty", dateTimeString)); - var timeSpanString = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty; - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, "TimeSpanProperty", timeSpanString)); - - var settingsRepository = new MyNullableSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - - private void GetSettings_GetsValues_FromCorrectSettings(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) - { - // Arrange - var expectedStringValue = stringValue ?? string.Empty; - var moduleInfo = GetModuleInfo; - var portalSettings = new Dictionary { ["IntegerProperty"] = integerValue?.ToString() ?? string.Empty, }; - var moduleSettings = new Hashtable { ["DateTimeProperty"] = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty, ["StringProperty"] = expectedStringValue, }; - var tabModuleSettings = new Hashtable { ["TimeSpanProperty"] = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty, }; - - this.MockPortalSettings(moduleInfo, portalSettings); - this.MockModuleSettings(moduleInfo, moduleSettings); - this.MockTabModuleSettings(moduleInfo, tabModuleSettings); - - var settingsRepository = new MyNullableSettingsRepository(); - - // Act - var settings = settingsRepository.GetSettings(moduleInfo); - - // Assert - Assert.AreEqual(expectedStringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); - Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); - Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); - Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); - this.MockRepository.VerifyAll(); - } - - public class MyNullableSettings - { - [ModuleSetting] - public string StringProperty { get; set; } = "Default Value"; - - [PortalSetting] - public int? IntegerProperty { get; set; } = 500; - - [ModuleSetting] - public DateTime? DateTimeProperty { get; set; } = DateTime.MaxValue; - - [TabModuleSetting] - public TimeSpan? TimeSpanProperty { get; set; } = TimeSpan.FromHours(12); - } - - public class MyNullableSettingsRepository : SettingsRepository - {} - } -} +namespace DotNetNuke.Tests.Core.Entities.Modules.Settings +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules.Settings; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class NullableSettingsTests : BaseSettingsTests + { + public readonly object[] NullableCases = + { + new object[] { null, null, null, null, }, + new object[] { string.Empty, -1, DateTime.UtcNow, TimeSpan.FromMilliseconds(3215648), }, + new object[] { "lorem ipsum", 456, DateTime.Now, DateTime.Today - DateTime.Now, }, + }; + + [SetUp] + public void Setup() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdateSetting_WithRightParameters_ar_JO(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdateSetting_WithRightParameters_ca_ES(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdateSetting_WithRightParameters_zh_CN(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("en-US")] + public void SaveSettings_CallsUpdateSetting_WithRightParameters_en_US(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("fr-FR")] + public void SaveSettings_CallsUpdateSetting_WithRightParameters_fr_FR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("he-IL")] + public void SaveSettings_CallsUpdateSetting_WithRightParameters_he_IL(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("ru-RU")] + public void SaveSettings_CallsUpdateSetting_WithRightParameters_ru_RU(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("tr-TR")] + public void SaveSettings_CallsUpdateSetting_WithRightParameters_tr_TR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + public void SaveSettings_UpdatesCache() + { + // Arrange + var moduleInfo = GetModuleInfo; + var settings = new MyNullableSettings(); + + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + var settingsRepository = new MyNullableSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + [Test] + public void GetSettings_CallsGetCachedObject() + { + // Arrange + var moduleInfo = GetModuleInfo; + + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyNullableSettings()); + var settingsRepository = new MyNullableSettingsRepository(); + + // Act + settingsRepository.GetSettings(moduleInfo); + + // Assert + this.MockRepository.VerifyAll(); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("ar-JO")] + public void GetSettings_GetsValues_FromCorrectSettings_ar_JO(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("ca-ES")] + public void GetSettings_GetsValues_FromCorrectSettings_ca_ES(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("zh-CN")] + public void GetSettings_GetsValues_FromCorrectSettings_zh_CN(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("en-US")] + public void GetSettings_GetsValues_FromCorrectSettings_en_US(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("fr-FR")] + public void GetSettings_GetsValues_FromCorrectSettings_fr_FR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("he-IL")] + public void GetSettings_GetsValues_FromCorrectSettings_he_IL(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("ru-RU")] + public void GetSettings_GetsValues_FromCorrectSettings_ru_RU(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + [Test] + [TestCaseSource(nameof(NullableCases))] + [SetCulture("tr-TR")] + public void GetSettings_GetsValues_FromCorrectSettings_tr_TR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + } + + private void SaveSettings_CallsUpdateSetting_WithRightParameters(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + // Arrange + var moduleInfo = GetModuleInfo; + var settings = new MyNullableSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + }; + + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + var expectedStringValue = stringValue ?? string.Empty; + this.MockModuleController.Setup(pc => pc.UpdateModuleSetting(ModuleId, "StringProperty", expectedStringValue)); + var integerString = integerValue?.ToString() ?? string.Empty; + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, "IntegerProperty", integerString, true, Null.NullString, false)); + var dateTimeString = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty; + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, "DateTimeProperty", dateTimeString)); + var timeSpanString = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty; + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, "TimeSpanProperty", timeSpanString)); + + var settingsRepository = new MyNullableSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + private void GetSettings_GetsValues_FromCorrectSettings(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + { + // Arrange + var expectedStringValue = stringValue ?? string.Empty; + var moduleInfo = GetModuleInfo; + var portalSettings = new Dictionary { ["IntegerProperty"] = integerValue?.ToString() ?? string.Empty, }; + var moduleSettings = new Hashtable { ["DateTimeProperty"] = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty, ["StringProperty"] = expectedStringValue, }; + var tabModuleSettings = new Hashtable { ["TimeSpanProperty"] = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty, }; + + this.MockPortalSettings(moduleInfo, portalSettings); + this.MockModuleSettings(moduleInfo, moduleSettings); + this.MockTabModuleSettings(moduleInfo, tabModuleSettings); + + var settingsRepository = new MyNullableSettingsRepository(); + + // Act + var settings = settingsRepository.GetSettings(moduleInfo); + + // Assert + Assert.AreEqual(expectedStringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); + Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); + Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); + Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); + this.MockRepository.VerifyAll(); + } + + public class MyNullableSettings + { + [ModuleSetting] + public string StringProperty { get; set; } = "Default Value"; + + [PortalSetting] + public int? IntegerProperty { get; set; } = 500; + + [ModuleSetting] + public DateTime? DateTimeProperty { get; set; } = DateTime.MaxValue; + + [TabModuleSetting] + public TimeSpan? TimeSpanProperty { get; set; } = TimeSpan.FromHours(12); + } + + public class MyNullableSettingsRepository : SettingsRepository + {} + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs index 725631066b8..d61e3644e80 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs @@ -2,280 +2,303 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Entities.Modules.Settings -{ - using System; - using System.Collections.Generic; - using System.Globalization; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Modules.Settings; - using DotNetNuke.Entities.Portals; - using Moq; - using NUnit.Framework; - - [TestFixture] - public class PortalSettingsTests : BaseSettingsTests - { - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("en-US")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("fr-FR")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("he-IL")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ru-RU")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("tr-TR")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - public void SaveSettings_UpdatesCache() - { - // Arrange - var moduleInfo = GetModuleInfo; - var settings = new MyPortalSettings(); - - this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); - var settingsRepository = new MyPortalSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - - [Test] - public void GetSettings_CallsGetCachedObject() - { - // Arrange - var moduleInfo = GetModuleInfo; - - this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyPortalSettings()); - var settingsRepository = new MyPortalSettingsRepository(); - - // Act - settingsRepository.GetSettings(moduleInfo); - - // Assert - this.MockRepository.VerifyAll(); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void GetSettings_GetsValuesFrom_PortalSettings_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void GetSettings_GetsValuesFrom_PortalSettings_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void GetSettings_GetsValuesFrom_PortalSettings_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("en-US")] - public void GetSettings_GetsValuesFrom_PortalSettings_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("fr-FR")] - public void GetSettings_GetsValuesFrom_PortalSettings_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("he-IL")] - public void GetSettings_GetsValuesFrom_PortalSettings_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ru-RU")] - public void GetSettings_GetsValuesFrom_PortalSettings_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("tr-TR")] - public void GetSettings_GetsValuesFrom_PortalSettings_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - private void SaveSettings_CallsUpdatePortalSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, - bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - // Arrange - var moduleInfo = GetModuleInfo; - var settings = new MyPortalSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DoubleProperty = doubleValue, - BooleanProperty = booleanValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - EnumProperty = enumValue, - ComplexProperty = complexValue, - }; - - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "StringProperty", stringValue, true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "IntegerProperty", integerValue.ToString(), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString(), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "EnumProperty", enumValue.ToString(), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}", true, Null.NullString, false)); - - var settingsRepository = new MyPortalSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - - private void GetSettings_GetsValuesFrom_PortalSettings(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - // Arrange - var moduleInfo = GetModuleInfo; - var portalSettings = new Dictionary - { - { SettingNamePrefix + "StringProperty", stringValue }, - { SettingNamePrefix + "IntegerProperty", integerValue.ToString() }, - { SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "BooleanProperty", booleanValue.ToString() }, - { SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "EnumProperty", enumValue.ToString() }, - { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, - }; - - this.MockPortalSettings(moduleInfo, portalSettings); - - var settingsRepository = new MyPortalSettingsRepository(); - - // Act - var settings = settingsRepository.GetSettings(moduleInfo); - - // Assert - Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); - Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); - Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); - Assert.AreEqual(booleanValue, settings.BooleanProperty, "The retrieved boolean property value is not equal to the stored one"); - Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); - Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); - Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); - Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); - this.MockRepository.VerifyAll(); - } - - public class MyPortalSettings - { - [PortalSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = string.Empty; - - [PortalSetting(Prefix = SettingNamePrefix)] - public int IntegerProperty { get; set; } - - [PortalSetting(Prefix = SettingNamePrefix)] - public double DoubleProperty { get; set; } - - [PortalSetting(Prefix = SettingNamePrefix)] - public bool BooleanProperty { get; set; } - - [PortalSetting(Prefix = SettingNamePrefix)] - public DateTime DateTimeProperty { get; set; } = DateTime.Now; - - [PortalSetting(Prefix = SettingNamePrefix)] - public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; - - [PortalSetting(Prefix = SettingNamePrefix)] - public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; - - [PortalSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] - public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); - } - - public class MyPortalSettingsRepository : SettingsRepository - {} - } -} +namespace DotNetNuke.Tests.Core.Entities.Modules.Settings +{ + using System; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules.Settings; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class PortalSettingsTests : BaseSettingsTests + { + [SetUp] + public void Setup() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("en-US")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("fr-FR")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("he-IL")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ru-RU")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("tr-TR")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + public void SaveSettings_UpdatesCache() + { + // Arrange + var moduleInfo = GetModuleInfo; + var settings = new MyPortalSettings(); + + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + var settingsRepository = new MyPortalSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + [Test] + public void GetSettings_CallsGetCachedObject() + { + // Arrange + var moduleInfo = GetModuleInfo; + + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyPortalSettings()); + var settingsRepository = new MyPortalSettingsRepository(); + + // Act + settingsRepository.GetSettings(moduleInfo); + + // Assert + this.MockRepository.VerifyAll(); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void GetSettings_GetsValuesFrom_PortalSettings_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void GetSettings_GetsValuesFrom_PortalSettings_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void GetSettings_GetsValuesFrom_PortalSettings_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("en-US")] + public void GetSettings_GetsValuesFrom_PortalSettings_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("fr-FR")] + public void GetSettings_GetsValuesFrom_PortalSettings_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("he-IL")] + public void GetSettings_GetsValuesFrom_PortalSettings_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ru-RU")] + public void GetSettings_GetsValuesFrom_PortalSettings_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("tr-TR")] + public void GetSettings_GetsValuesFrom_PortalSettings_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + private void SaveSettings_CallsUpdatePortalSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, + bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + // Arrange + var moduleInfo = GetModuleInfo; + var settings = new MyPortalSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; + + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "StringProperty", stringValue, true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "IntegerProperty", integerValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "EnumProperty", enumValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}", true, Null.NullString, false)); + + var settingsRepository = new MyPortalSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + private void GetSettings_GetsValuesFrom_PortalSettings(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + // Arrange + var moduleInfo = GetModuleInfo; + var portalSettings = new Dictionary + { + { SettingNamePrefix + "StringProperty", stringValue }, + { SettingNamePrefix + "IntegerProperty", integerValue.ToString() }, + { SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "BooleanProperty", booleanValue.ToString() }, + { SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "EnumProperty", enumValue.ToString() }, + { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, + }; + + this.MockPortalSettings(moduleInfo, portalSettings); + + var settingsRepository = new MyPortalSettingsRepository(); + + // Act + var settings = settingsRepository.GetSettings(moduleInfo); + + // Assert + Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); + Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); + Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); + Assert.AreEqual(booleanValue, settings.BooleanProperty, "The retrieved boolean property value is not equal to the stored one"); + Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); + Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); + Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); + Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); + this.MockRepository.VerifyAll(); + } + + public class MyPortalSettings + { + [PortalSetting(Prefix = SettingNamePrefix)] + public string StringProperty { get; set; } = string.Empty; + + [PortalSetting(Prefix = SettingNamePrefix)] + public int IntegerProperty { get; set; } + + [PortalSetting(Prefix = SettingNamePrefix)] + public double DoubleProperty { get; set; } + + [PortalSetting(Prefix = SettingNamePrefix)] + public bool BooleanProperty { get; set; } + + [PortalSetting(Prefix = SettingNamePrefix)] + public DateTime DateTimeProperty { get; set; } = DateTime.Now; + + [PortalSetting(Prefix = SettingNamePrefix)] + public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; + + [PortalSetting(Prefix = SettingNamePrefix)] + public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; + + [PortalSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] + public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); + } + + public class MyPortalSettingsRepository : SettingsRepository + {} + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs index 5d7ed767a43..cc799b4d0bb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs @@ -2,282 +2,304 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Entities.Modules.Settings -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Globalization; - - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Modules.Settings; - using Moq; - using NUnit.Framework; - - [TestFixture] - public class TabModuleSettingsTests : BaseSettingsTests - { - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("en-US")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("fr-FR")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("he-IL")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ru-RU")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("tr-TR")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - public void SaveSettings_UpdatesCache() - { - // Arrange - var moduleInfo = GetModuleInfo; - var settings = new MyTabModuleSettings(); - - this.MockTabModuleSettings(moduleInfo, new Hashtable()); - this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); - var settingsRepository = new MyTabModuleSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - - [Test] - public void GetSettings_CallsGetCachedObject() - { - // Arrange - var moduleInfo = GetModuleInfo; - - this.MockTabModuleSettings(moduleInfo, new Hashtable()); - this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyTabModuleSettings()); - var settingsRepository = new MyTabModuleSettingsRepository(); - - // Act - settingsRepository.GetSettings(moduleInfo); - - // Assert - this.MockRepository.VerifyAll(); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("en-US")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("fr-FR")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("he-IL")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ru-RU")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("tr-TR")] - public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - private void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - // Arrange - var moduleInfo = GetModuleInfo; - var settings = new MyTabModuleSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DoubleProperty = doubleValue, - BooleanProperty = booleanValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - EnumProperty = enumValue, - ComplexProperty = complexValue, - }; - - this.MockTabModuleSettings(moduleInfo, new Hashtable()); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "StringProperty", stringValue)); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); - - var settingsRepository = new MyTabModuleSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - - private void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - // Arrange - var moduleInfo = GetModuleInfo; - var tabModuleSettings = new Hashtable - { - { SettingNamePrefix + "StringProperty", stringValue }, - { SettingNamePrefix + "IntegerProperty", integerValue.ToString() }, - { SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "BooleanProperty", booleanValue.ToString() }, - { SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture) }, - { SettingNamePrefix + "EnumProperty", enumValue.ToString() }, - { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, - }; - - this.MockTabModuleSettings(moduleInfo, tabModuleSettings); - - var settingsRepository = new MyTabModuleSettingsRepository(); - - // Act - var settings = settingsRepository.GetSettings(moduleInfo); - - // Assert - Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); - Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); - Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); - Assert.AreEqual(booleanValue, settings.BooleanProperty, "The retrieved boolean property value is not equal to the stored one"); - Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); - Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); - Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); - Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); - this.MockRepository.VerifyAll(); - } - - public class MyTabModuleSettings - { - [TabModuleSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = string.Empty; - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public int IntegerProperty { get; set; } - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public double DoubleProperty { get; set; } - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public bool BooleanProperty { get; set; } - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public DateTime DateTimeProperty { get; set; } = DateTime.Now; - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; - - [TabModuleSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] - public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); - } - - public class MyTabModuleSettingsRepository : SettingsRepository - {} - } -} +namespace DotNetNuke.Tests.Core.Entities.Modules.Settings +{ + using System; + using System.Collections; + using System.Globalization; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules.Settings; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class TabModuleSettingsTests : BaseSettingsTests + { + [SetUp] + public void Setup() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("en-US")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("fr-FR")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("he-IL")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ru-RU")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("tr-TR")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + public void SaveSettings_UpdatesCache() + { + // Arrange + var moduleInfo = GetModuleInfo; + var settings = new MyTabModuleSettings(); + + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + var settingsRepository = new MyTabModuleSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + [Test] + public void GetSettings_CallsGetCachedObject() + { + // Arrange + var moduleInfo = GetModuleInfo; + + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyTabModuleSettings()); + var settingsRepository = new MyTabModuleSettingsRepository(); + + // Act + settingsRepository.GetSettings(moduleInfo); + + // Assert + this.MockRepository.VerifyAll(); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("en-US")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("fr-FR")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("he-IL")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ru-RU")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("tr-TR")] + public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + private void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + // Arrange + var moduleInfo = GetModuleInfo; + var settings = new MyTabModuleSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; + + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "StringProperty", stringValue)); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); + + var settingsRepository = new MyTabModuleSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + private void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + // Arrange + var moduleInfo = GetModuleInfo; + var tabModuleSettings = new Hashtable + { + { SettingNamePrefix + "StringProperty", stringValue }, + { SettingNamePrefix + "IntegerProperty", integerValue.ToString() }, + { SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "BooleanProperty", booleanValue.ToString() }, + { SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture) }, + { SettingNamePrefix + "EnumProperty", enumValue.ToString() }, + { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, + }; + + this.MockTabModuleSettings(moduleInfo, tabModuleSettings); + + var settingsRepository = new MyTabModuleSettingsRepository(); + + // Act + var settings = settingsRepository.GetSettings(moduleInfo); + + // Assert + Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); + Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); + Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); + Assert.AreEqual(booleanValue, settings.BooleanProperty, "The retrieved boolean property value is not equal to the stored one"); + Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); + Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); + Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); + Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); + this.MockRepository.VerifyAll(); + } + + public class MyTabModuleSettings + { + [TabModuleSetting(Prefix = SettingNamePrefix)] + public string StringProperty { get; set; } = string.Empty; + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public int IntegerProperty { get; set; } + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public double DoubleProperty { get; set; } + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public bool BooleanProperty { get; set; } + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public DateTime DateTimeProperty { get; set; } = DateTime.Now; + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; + + [TabModuleSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] + public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); + } + + public class MyTabModuleSettingsRepository : SettingsRepository + {} + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs index dc91cadca39..029e2f61718 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs @@ -2,636 +2,627 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Entities.Portals -{ - using System; - using System.Collections.Generic; - using System.Reflection; - using System.Runtime.Serialization; +namespace DotNetNuke.Tests.Core.Entities.Portals +{ + using System; + using System.Collections.Generic; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Tabs; - using DotNetNuke.Services.Localization; - using DotNetNuke.Tests.Utilities.Mocks; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + using DotNetNuke.Tests.Utilities.Mocks; using DotNetNuke.UI.Skins; + using Microsoft.Extensions.DependencyInjection; - using Moq; - using NUnit.Framework; - - [TestFixture] - public class PortalSettingsControllerTests - { - private const int HostPortalId = -1; - private const int HostTabId = 24; - private const int ValidPortalId = 0; - private const int ValidTabId = 42; - private const int ParentTabId = 55; - private const int SplashTabId = 41; - private const int HomeTabId = 40; - private const int InValidTabId = -1; - - private const string DefaultSkin = "DefaultSkin"; - private const string TabSkin = "TabSkin"; - private const string GlobalTabSkin = "[g]TabSkin"; - - private const string DefaultContainer = "DefaultContainer"; - private const string TabContainer = "TabContainer"; - private const string GlobalTabContainer = "[g]TabContainer"; - - [SetUp] - public void SetUp() - { - MockComponentProvider.ResetContainer(); - - var serviceCollection = new ServiceCollection(); - var mockApplicationInfo = new Mock(); - mockApplicationInfo.Setup(info => info.ApplicationMapPath).Returns("path/to/application"); - serviceCollection.AddTransient(container => mockApplicationInfo.Object); - serviceCollection.AddTransient(container => Mock.Of()); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - } - - [TearDown] - public void TearDown() - { - PortalController.ClearInstance(); - TabController.ClearInstance(); - Globals.DependencyProvider = null; - - } - - [Test] - [TestCaseSource(typeof(PortalSettingsControllerTestFactory), "LoadPortalSettings_Loads_Default_Value")] - public void LoadPortalSettings_Loads_Default_Value(Dictionary testFields) - { - // Arrange - var propertyName = testFields["PropertyName"]; - var settingName = testFields["SettingName"]; - var isHostDefault = bool.Parse(testFields["IsHostDefault"]); - var defaultValue = testFields["DefaultValue"]; - var controller = new PortalSettingsController(); - var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); - - var mockPortalController = new Mock(); - mockPortalController - .Setup(c => c.GetPortalSettings(It.IsAny())) - .Returns(new Dictionary()); - PortalController.SetTestableInstance(mockPortalController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString(It.IsAny())) - .Returns((string s) => hostSettings[s]); - mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) - .Returns((string s1, string s2) => hostSettings[s1]); - mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) - .Returns((string s, bool b) => bool.Parse(hostSettings[s])); - mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) - .Returns((string s, int i) => int.Parse(hostSettings[s])); - mockHostController.Setup(c => c.GetInteger(It.IsAny())) - .Returns((string s) => int.Parse(hostSettings[s])); - HostController.RegisterInstance(mockHostController.Object); - - if (isHostDefault) - { - defaultValue = hostSettings[settingName]; - } - - // Act - controller.LoadPortalSettings(settings); - - // Assert - var property = settings.GetType().GetProperty(propertyName); - var actualValue = property.GetValue(settings, null); - if (actualValue is bool) - { - Assert.AreEqual(defaultValue, actualValue.ToString().ToLowerInvariant()); - } - else - { - Assert.AreEqual(defaultValue, actualValue.ToString()); - } - } - - [Test] - [TestCaseSource(typeof(PortalSettingsControllerTestFactory), "LoadPortalSettings_Loads_Setting_Value")] - public void LoadPortalSettings_Loads_Setting_Value(Dictionary testFields) - { - // Arrange - var propertyName = testFields["PropertyName"]; - var settingName = testFields["SettingName"]; - var settingValue = testFields["SettingValue"]; - var propertyValue = testFields.ContainsKey("PropertyValue") ? testFields["PropertyValue"] : settingValue; - var controller = new PortalSettingsController(); - var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); - - var mockPortalController = new Mock(); - mockPortalController - .Setup(c => c.GetPortalSettings(It.IsAny())) - .Returns(new Dictionary { { settingName, settingValue } }); - PortalController.SetTestableInstance(mockPortalController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString(It.IsAny())) - .Returns((string s) => hostSettings[s]); - mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) - .Returns((string s1, string s2) => hostSettings[s1]); - mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) - .Returns((string s, bool b) => bool.Parse(hostSettings[s])); - mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) - .Returns((string s, int i) => int.Parse(hostSettings[s])); - HostController.RegisterInstance(mockHostController.Object); - - // Act - controller.LoadPortalSettings(settings); - - // Assert - var property = settings.GetType().GetProperty(propertyName); - var actualValue = property.GetValue(settings, null); - if (actualValue is bool) - { - Assert.AreEqual(propertyValue, actualValue.ToString().ToLowerInvariant()); - } - else - { - Assert.AreEqual(propertyValue, actualValue.ToString()); - } - } - - [Test] - public void LoadPortalSettings_Sets_TimeZone_Property_To_Local_TimeZone() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); - - var mockPortalController = new Mock(); - mockPortalController - .Setup(c => c.GetPortalSettings(It.IsAny())) - .Returns(new Dictionary()); - PortalController.SetTestableInstance(mockPortalController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString(It.IsAny())) - .Returns((string s) => hostSettings[s]); - mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) - .Returns((string s1, string s2) => hostSettings[s1]); - mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) - .Returns((string s, bool b) => bool.Parse(hostSettings[s])); - mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) - .Returns((string s, int i) => int.Parse(hostSettings[s])); - HostController.RegisterInstance(mockHostController.Object); - - // Act - controller.LoadPortalSettings(settings); - - // Assert - Assert.AreEqual(TimeZoneInfo.Local, settings.TimeZone); - } - - [Test] - public void LoadPortal_Loads_Portal_Property_Values() - { - // Arrange - var controller = new PortalSettingsController(); - var portal = new PortalInfo() - { - Users = 2, - Pages = 5, - DefaultLanguage = Localization.SystemLocale, - HomeDirectory = "Portals/0", - }; - var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; - - // Act - controller.LoadPortal(portal, settings); - - // Assert - Assert.AreEqual(portal.AdminTabId, settings.AdminTabId); - Assert.AreEqual(portal.AdministratorId, settings.AdministratorId); - Assert.AreEqual(portal.AdministratorRoleId, settings.AdministratorRoleId); - Assert.AreEqual(portal.AdministratorRoleName, settings.AdministratorRoleName); - Assert.AreEqual(portal.BackgroundFile, settings.BackgroundFile); - Assert.AreEqual(portal.BannerAdvertising, settings.BannerAdvertising); - Assert.AreEqual(portal.CultureCode, settings.CultureCode); - Assert.AreEqual(portal.Currency, settings.Currency); - Assert.AreEqual(portal.Custom404TabId, settings.ErrorPage404); - Assert.AreEqual(portal.Custom500TabId, settings.ErrorPage500); - Assert.AreEqual(portal.TermsTabId, settings.TermsTabId); - Assert.AreEqual(portal.PrivacyTabId, settings.PrivacyTabId); - Assert.AreEqual(portal.DefaultLanguage, settings.DefaultLanguage); - Assert.AreEqual(portal.Description, settings.Description); - Assert.AreEqual(portal.Email, settings.Email); - Assert.AreEqual(portal.ExpiryDate, settings.ExpiryDate); - Assert.AreEqual(portal.FooterText, settings.FooterText); - Assert.AreEqual(portal.GUID, settings.GUID); - Assert.AreEqual(Globals.ApplicationPath + "/" + portal.HomeDirectory + "/", settings.HomeDirectory); - Assert.AreEqual(portal.HomeDirectoryMapPath, settings.HomeDirectoryMapPath); - Assert.AreEqual(Globals.ApplicationPath + "/" + portal.HomeSystemDirectory + "/", settings.HomeSystemDirectory); - Assert.AreEqual(portal.HomeSystemDirectoryMapPath, settings.HomeSystemDirectoryMapPath); - Assert.AreEqual(portal.HomeTabId, settings.HomeTabId); - Assert.AreEqual(portal.HostFee, settings.HostFee); - Assert.AreEqual(portal.HostSpace, settings.HostSpace); - Assert.AreEqual(portal.KeyWords, settings.KeyWords); - Assert.AreEqual(portal.LoginTabId, settings.LoginTabId); - Assert.AreEqual(portal.LogoFile, settings.LogoFile); - Assert.AreEqual(portal.PageQuota, settings.PageQuota); - Assert.AreEqual(portal.Pages, settings.Pages); - Assert.AreEqual(portal.PortalName, settings.PortalName); - Assert.AreEqual(portal.RegisterTabId, settings.RegisterTabId); - Assert.AreEqual(portal.RegisteredRoleId, settings.RegisteredRoleId); - Assert.AreEqual(portal.RegisteredRoleName, settings.RegisteredRoleName); - Assert.AreEqual(portal.SearchTabId, settings.SearchTabId); - Assert.AreEqual(portal.SplashTabId, settings.SplashTabId); - Assert.AreEqual(portal.SuperTabId, settings.SuperTabId); - Assert.AreEqual(portal.UserQuota, settings.UserQuota); - Assert.AreEqual(portal.UserRegistration, settings.UserRegistration); - Assert.AreEqual(portal.UserTabId, settings.UserTabId); - Assert.AreEqual(portal.Users, settings.Users); - } - - [Test] - public void GetActiveTab_Gets_Correct_Tab_If_Valid_Portal_TabId() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - var tab = controller.GetActiveTab(ValidTabId, settings); - - // Assert - Assert.AreEqual(validTab.TabID, tab.TabID); - } - - [Test] - public void GetActiveTab_Gets_Correct_Tab_If_Valid_Host_TabId() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = HostTabId, PortalID = HostPortalId }; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - var tab = controller.GetActiveTab(HostTabId, settings); - - // Assert - Assert.AreEqual(validTab.TabID, tab.TabID); - } - - [Test] - public void GetActiveTab_Gets_Splash_Tab_If_InValid_TabId_And_SplashTab_Set() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, SplashTabId = SplashTabId, CultureCode = Null.NullString }; - var splashTabId = new TabInfo { TabID = SplashTabId, PortalID = ValidPortalId }; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(ValidPortalId)).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { splashTabId })); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - var tab = controller.GetActiveTab(InValidTabId, settings); - - // Assert - Assert.AreEqual(SplashTabId, tab.TabID); - } - - [Test] - public void GetActiveTab_Gets_Home_Tab_If_InValid_TabId_And_Home_Set() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, HomeTabId = HomeTabId, CultureCode = Null.NullString }; - var homeTabId = new TabInfo { TabID = HomeTabId, PortalID = ValidPortalId }; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(ValidPortalId)).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { homeTabId })); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - var tab = controller.GetActiveTab(InValidTabId, settings); - - // Assert - Assert.AreEqual(HomeTabId, tab.TabID); - } - - [Test] - public void GetActiveTab_Gets_Splash_Tab_If_InValid_TabId_And_Both_HomeTab_And_SplashTab_Set() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, SplashTabId = SplashTabId, HomeTabId = HomeTabId, CultureCode = Null.NullString }; - var splashTabId = new TabInfo { TabID = SplashTabId, PortalID = ValidPortalId }; - var homeTabId = new TabInfo { TabID = HomeTabId, PortalID = ValidPortalId }; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(ValidPortalId)).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { splashTabId, homeTabId })); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - var tab = controller.GetActiveTab(InValidTabId, settings); - - // Assert - Assert.AreEqual(SplashTabId, tab.TabID); - } - - [Test] - public void GetActiveTab_Sets_StartDate_And_EndDate_Of_Tab_If_Not_Set() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - var tab = controller.GetActiveTab(ValidTabId, settings); - - // Assert - Assert.AreEqual(DateTime.MinValue, tab.StartDate); - Assert.AreEqual(DateTime.MaxValue, tab.EndDate); - } - - [Test] - public void ConfigureTab_Uses_PortalSettings_DefaultSkin_If_SkinSrc_Not_Set() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; - settings.ActiveTab = validTab; - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString("DefaultPortalSkin")).Returns(DefaultSkin); - mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); - HostController.RegisterInstance(mockHostController.Object); - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - controller.ConfigureActiveTab(settings); - - // Assert - Assert.AreEqual(DefaultSkin, settings.ActiveTab.SkinSrc); - } - - [Test] - public void ConfigureTab_Uses_Tab_SkinSrc_If_SkinSrc_Set() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = TabSkin }; - settings.ActiveTab = validTab; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); - HostController.RegisterInstance(mockHostController.Object); - - // Act - controller.ConfigureActiveTab(settings); - - // Assert - Assert.AreEqual(TabSkin, settings.ActiveTab.SkinSrc); - } - - [Test] - public void ConfigureTab_Formats_Tab_SkinSrc_If_Neccessary() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = GlobalTabSkin }; - settings.ActiveTab = validTab; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); - HostController.RegisterInstance(mockHostController.Object); - - // Act - controller.ConfigureActiveTab(settings); - - // Assert - Assert.AreEqual(SkinController.FormatSkinSrc(GlobalTabSkin, settings), settings.ActiveTab.SkinSrc); - } - - [Test] - public void ConfigureTab_Uses_PortalSettings_DefaultContainer_If_ContainerSrc_Not_Set() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; - settings.ActiveTab = validTab; - settings.ActiveTab.SkinSrc = TabSkin; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); - HostController.RegisterInstance(mockHostController.Object); - - // Act - controller.ConfigureActiveTab(settings); - - // Assert - Assert.AreEqual(DefaultContainer, settings.ActiveTab.ContainerSrc); - } - - [Test] - public void ConfigureTab_Uses_Tab_ContainerSrc_If_ContainerSrc_Set() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ContainerSrc = TabContainer }; - settings.ActiveTab = validTab; - settings.ActiveTab.SkinSrc = TabSkin; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - controller.ConfigureActiveTab(settings); - - // Assert - Assert.AreEqual(TabContainer, settings.ActiveTab.ContainerSrc); - } - - [Test] - public void ConfigureTab_Formats_Tab_ContainerSrc_If_Neccessary() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ContainerSrc = GlobalTabContainer }; - settings.ActiveTab = validTab; - settings.ActiveTab.SkinSrc = TabSkin; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - // Act - controller.ConfigureActiveTab(settings); - - // Assert - Assert.AreEqual(SkinController.FormatSkinSrc(GlobalTabContainer, settings), settings.ActiveTab.ContainerSrc); - } - - [Test] - public void ConfigureTab_Builds_Breadcrumbs_For_Tab() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = GlobalTabSkin }; - settings.ActiveTab = validTab; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); - HostController.RegisterInstance(mockHostController.Object); - - // Act - controller.ConfigureActiveTab(settings); - - // Assert - Assert.NotNull(settings.ActiveTab.BreadCrumbs); - Assert.AreEqual(1, settings.ActiveTab.BreadCrumbs.Count); - } - - [Test] - public void ConfigureTab_Builds_Breadcrumbs_For_Tab_And_Parent() - { - // Arrange - var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ParentId = ParentTabId }; - var parentTab = new TabInfo { TabID = ParentTabId, PortalID = ValidPortalId }; - settings.ActiveTab = validTab; - settings.ActiveTab.SkinSrc = TabSkin; - - var mockLocaleController = new Mock(); - mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); - LocaleController.RegisterInstance(mockLocaleController.Object); - - var mockTabController = new Mock(); - mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab, parentTab })); - mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); - TabController.SetTestableInstance(mockTabController.Object); - - var mockHostController = new Mock(); - mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); - HostController.RegisterInstance(mockHostController.Object); - - // Act - controller.ConfigureActiveTab(settings); - - // Assert - var actualParent = settings.ActiveTab.BreadCrumbs[0] as TabInfo; - var actualTab = settings.ActiveTab.BreadCrumbs[1] as TabInfo; - Assert.AreEqual(2, settings.ActiveTab.BreadCrumbs.Count); - Assert.AreEqual(ValidTabId, actualTab.TabID); - Assert.AreEqual(ParentTabId, actualParent.TabID); - } - } -} + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class PortalSettingsControllerTests + { + private const int HostPortalId = -1; + private const int HostTabId = 24; + private const int ValidPortalId = 0; + private const int ValidTabId = 42; + private const int ParentTabId = 55; + private const int SplashTabId = 41; + private const int HomeTabId = 40; + private const int InValidTabId = -1; + + private const string DefaultSkin = "DefaultSkin"; + private const string TabSkin = "TabSkin"; + private const string GlobalTabSkin = "[g]TabSkin"; + + private const string DefaultContainer = "DefaultContainer"; + private const string TabContainer = "TabContainer"; + private const string GlobalTabContainer = "[g]TabContainer"; + + private Mock mockHostController; + + [SetUp] + public void SetUp() + { + MockComponentProvider.ResetContainer(); + + var serviceCollection = new ServiceCollection(); + var mockApplicationInfo = new Mock(); + mockApplicationInfo.Setup(info => info.ApplicationMapPath).Returns("path/to/application"); + + this.mockHostController = new Mock(); + this.mockHostController.As(); + + serviceCollection.AddTransient(container => mockApplicationInfo.Object); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => (IHostSettingsService)this.mockHostController.Object); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [TearDown] + public void TearDown() + { + PortalController.ClearInstance(); + TabController.ClearInstance(); + Globals.DependencyProvider = null; + + } + + [Test] + [TestCaseSource(typeof(PortalSettingsControllerTestFactory), "LoadPortalSettings_Loads_Default_Value")] + public void LoadPortalSettings_Loads_Default_Value(Dictionary testFields) + { + // Arrange + var propertyName = testFields["PropertyName"]; + var settingName = testFields["SettingName"]; + var isHostDefault = bool.Parse(testFields["IsHostDefault"]); + var defaultValue = testFields["DefaultValue"]; + var controller = new PortalSettingsController(); + var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; + var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); + + var mockPortalController = new Mock(); + mockPortalController + .Setup(c => c.GetPortalSettings(It.IsAny())) + .Returns(new Dictionary()); + PortalController.SetTestableInstance(mockPortalController.Object); + + this.mockHostController.Setup(c => c.GetString(It.IsAny())) + .Returns((string s) => hostSettings[s]); + this.mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) + .Returns((string s1, string s2) => hostSettings[s1]); + this.mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) + .Returns((string s, bool b) => bool.Parse(hostSettings[s])); + this.mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) + .Returns((string s, int i) => int.Parse(hostSettings[s])); + this.mockHostController.Setup(c => c.GetInteger(It.IsAny())) + .Returns((string s) => int.Parse(hostSettings[s])); + + if (isHostDefault) + { + defaultValue = hostSettings[settingName]; + } + + // Act + controller.LoadPortalSettings(settings); + + // Assert + var property = settings.GetType().GetProperty(propertyName); + var actualValue = property.GetValue(settings, null); + if (actualValue is bool) + { + Assert.AreEqual(defaultValue, actualValue.ToString().ToLowerInvariant()); + } + else + { + Assert.AreEqual(defaultValue, actualValue.ToString()); + } + } + + [Test] + [TestCaseSource(typeof(PortalSettingsControllerTestFactory), "LoadPortalSettings_Loads_Setting_Value")] + public void LoadPortalSettings_Loads_Setting_Value(Dictionary testFields) + { + // Arrange + var propertyName = testFields["PropertyName"]; + var settingName = testFields["SettingName"]; + var settingValue = testFields["SettingValue"]; + var propertyValue = testFields.ContainsKey("PropertyValue") ? testFields["PropertyValue"] : settingValue; + var controller = new PortalSettingsController(); + var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; + var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); + + var mockPortalController = new Mock(); + mockPortalController + .Setup(c => c.GetPortalSettings(It.IsAny())) + .Returns(new Dictionary { { settingName, settingValue } }); + PortalController.SetTestableInstance(mockPortalController.Object); + + this.mockHostController.Setup(c => c.GetString(It.IsAny())) + .Returns((string s) => hostSettings[s]); + this.mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) + .Returns((string s1, string s2) => hostSettings[s1]); + this.mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) + .Returns((string s, bool b) => bool.Parse(hostSettings[s])); + this.mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) + .Returns((string s, int i) => int.Parse(hostSettings[s])); + + // Act + controller.LoadPortalSettings(settings); + + // Assert + var property = settings.GetType().GetProperty(propertyName); + var actualValue = property.GetValue(settings, null); + if (actualValue is bool) + { + Assert.AreEqual(propertyValue, actualValue.ToString().ToLowerInvariant()); + } + else + { + Assert.AreEqual(propertyValue, actualValue.ToString()); + } + } + + [Test] + public void LoadPortalSettings_Sets_TimeZone_Property_To_Local_TimeZone() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; + var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); + + var mockPortalController = new Mock(); + mockPortalController + .Setup(c => c.GetPortalSettings(It.IsAny())) + .Returns(new Dictionary()); + PortalController.SetTestableInstance(mockPortalController.Object); + + this.mockHostController.Setup(c => c.GetString(It.IsAny())) + .Returns((string s) => hostSettings[s]); + this.mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) + .Returns((string s1, string s2) => hostSettings[s1]); + this.mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) + .Returns((string s, bool b) => bool.Parse(hostSettings[s])); + this.mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) + .Returns((string s, int i) => int.Parse(hostSettings[s])); + + // Act + controller.LoadPortalSettings(settings); + + // Assert + Assert.AreEqual(TimeZoneInfo.Local, settings.TimeZone); + } + + [Test] + public void LoadPortal_Loads_Portal_Property_Values() + { + // Arrange + var controller = new PortalSettingsController(); + var portal = new PortalInfo() + { + Users = 2, + Pages = 5, + DefaultLanguage = Localization.SystemLocale, + HomeDirectory = "Portals/0", + }; + var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; + + // Act + controller.LoadPortal(portal, settings); + + // Assert + Assert.AreEqual(portal.AdminTabId, settings.AdminTabId); + Assert.AreEqual(portal.AdministratorId, settings.AdministratorId); + Assert.AreEqual(portal.AdministratorRoleId, settings.AdministratorRoleId); + Assert.AreEqual(portal.AdministratorRoleName, settings.AdministratorRoleName); + Assert.AreEqual(portal.BackgroundFile, settings.BackgroundFile); + Assert.AreEqual(portal.BannerAdvertising, settings.BannerAdvertising); + Assert.AreEqual(portal.CultureCode, settings.CultureCode); + Assert.AreEqual(portal.Currency, settings.Currency); + Assert.AreEqual(portal.Custom404TabId, settings.ErrorPage404); + Assert.AreEqual(portal.Custom500TabId, settings.ErrorPage500); + Assert.AreEqual(portal.TermsTabId, settings.TermsTabId); + Assert.AreEqual(portal.PrivacyTabId, settings.PrivacyTabId); + Assert.AreEqual(portal.DefaultLanguage, settings.DefaultLanguage); + Assert.AreEqual(portal.Description, settings.Description); + Assert.AreEqual(portal.Email, settings.Email); + Assert.AreEqual(portal.ExpiryDate, settings.ExpiryDate); + Assert.AreEqual(portal.FooterText, settings.FooterText); + Assert.AreEqual(portal.GUID, settings.GUID); + Assert.AreEqual(Globals.ApplicationPath + "/" + portal.HomeDirectory + "/", settings.HomeDirectory); + Assert.AreEqual(portal.HomeDirectoryMapPath, settings.HomeDirectoryMapPath); + Assert.AreEqual(Globals.ApplicationPath + "/" + portal.HomeSystemDirectory + "/", settings.HomeSystemDirectory); + Assert.AreEqual(portal.HomeSystemDirectoryMapPath, settings.HomeSystemDirectoryMapPath); + Assert.AreEqual(portal.HomeTabId, settings.HomeTabId); + Assert.AreEqual(portal.HostFee, settings.HostFee); + Assert.AreEqual(portal.HostSpace, settings.HostSpace); + Assert.AreEqual(portal.KeyWords, settings.KeyWords); + Assert.AreEqual(portal.LoginTabId, settings.LoginTabId); + Assert.AreEqual(portal.LogoFile, settings.LogoFile); + Assert.AreEqual(portal.PageQuota, settings.PageQuota); + Assert.AreEqual(portal.Pages, settings.Pages); + Assert.AreEqual(portal.PortalName, settings.PortalName); + Assert.AreEqual(portal.RegisterTabId, settings.RegisterTabId); + Assert.AreEqual(portal.RegisteredRoleId, settings.RegisteredRoleId); + Assert.AreEqual(portal.RegisteredRoleName, settings.RegisteredRoleName); + Assert.AreEqual(portal.SearchTabId, settings.SearchTabId); + Assert.AreEqual(portal.SplashTabId, settings.SplashTabId); + Assert.AreEqual(portal.SuperTabId, settings.SuperTabId); + Assert.AreEqual(portal.UserQuota, settings.UserQuota); + Assert.AreEqual(portal.UserRegistration, settings.UserRegistration); + Assert.AreEqual(portal.UserTabId, settings.UserTabId); + Assert.AreEqual(portal.Users, settings.Users); + } + + [Test] + public void GetActiveTab_Gets_Correct_Tab_If_Valid_Portal_TabId() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + var tab = controller.GetActiveTab(ValidTabId, settings); + + // Assert + Assert.AreEqual(validTab.TabID, tab.TabID); + } + + [Test] + public void GetActiveTab_Gets_Correct_Tab_If_Valid_Host_TabId() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = HostTabId, PortalID = HostPortalId }; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + var tab = controller.GetActiveTab(HostTabId, settings); + + // Assert + Assert.AreEqual(validTab.TabID, tab.TabID); + } + + [Test] + public void GetActiveTab_Gets_Splash_Tab_If_InValid_TabId_And_SplashTab_Set() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, SplashTabId = SplashTabId, CultureCode = Null.NullString }; + var splashTabId = new TabInfo { TabID = SplashTabId, PortalID = ValidPortalId }; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(ValidPortalId)).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { splashTabId })); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + var tab = controller.GetActiveTab(InValidTabId, settings); + + // Assert + Assert.AreEqual(SplashTabId, tab.TabID); + } + + [Test] + public void GetActiveTab_Gets_Home_Tab_If_InValid_TabId_And_Home_Set() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, HomeTabId = HomeTabId, CultureCode = Null.NullString }; + var homeTabId = new TabInfo { TabID = HomeTabId, PortalID = ValidPortalId }; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(ValidPortalId)).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { homeTabId })); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + var tab = controller.GetActiveTab(InValidTabId, settings); + + // Assert + Assert.AreEqual(HomeTabId, tab.TabID); + } + + [Test] + public void GetActiveTab_Gets_Splash_Tab_If_InValid_TabId_And_Both_HomeTab_And_SplashTab_Set() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, SplashTabId = SplashTabId, HomeTabId = HomeTabId, CultureCode = Null.NullString }; + var splashTabId = new TabInfo { TabID = SplashTabId, PortalID = ValidPortalId }; + var homeTabId = new TabInfo { TabID = HomeTabId, PortalID = ValidPortalId }; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(ValidPortalId)).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { splashTabId, homeTabId })); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + var tab = controller.GetActiveTab(InValidTabId, settings); + + // Assert + Assert.AreEqual(SplashTabId, tab.TabID); + } + + [Test] + public void GetActiveTab_Sets_StartDate_And_EndDate_Of_Tab_If_Not_Set() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + var tab = controller.GetActiveTab(ValidTabId, settings); + + // Assert + Assert.AreEqual(DateTime.MinValue, tab.StartDate); + Assert.AreEqual(DateTime.MaxValue, tab.EndDate); + } + + [Test] + public void ConfigureTab_Uses_PortalSettings_DefaultSkin_If_SkinSrc_Not_Set() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; + settings.ActiveTab = validTab; + + this.mockHostController.Setup(c => c.GetString("DefaultPortalSkin")).Returns(DefaultSkin); + this.mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + controller.ConfigureActiveTab(settings); + + // Assert + Assert.AreEqual(DefaultSkin, settings.ActiveTab.SkinSrc); + } + + [Test] + public void ConfigureTab_Uses_Tab_SkinSrc_If_SkinSrc_Set() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = TabSkin }; + settings.ActiveTab = validTab; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + this.mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); + + // Act + controller.ConfigureActiveTab(settings); + + // Assert + Assert.AreEqual(TabSkin, settings.ActiveTab.SkinSrc); + } + + [Test] + public void ConfigureTab_Formats_Tab_SkinSrc_If_Neccessary() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = GlobalTabSkin }; + settings.ActiveTab = validTab; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + this.mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); + + // Act + controller.ConfigureActiveTab(settings); + + // Assert + Assert.AreEqual(SkinController.FormatSkinSrc(GlobalTabSkin, settings), settings.ActiveTab.SkinSrc); + } + + [Test] + public void ConfigureTab_Uses_PortalSettings_DefaultContainer_If_ContainerSrc_Not_Set() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; + settings.ActiveTab = validTab; + settings.ActiveTab.SkinSrc = TabSkin; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + this.mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); + + // Act + controller.ConfigureActiveTab(settings); + + // Assert + Assert.AreEqual(DefaultContainer, settings.ActiveTab.ContainerSrc); + } + + [Test] + public void ConfigureTab_Uses_Tab_ContainerSrc_If_ContainerSrc_Set() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ContainerSrc = TabContainer }; + settings.ActiveTab = validTab; + settings.ActiveTab.SkinSrc = TabSkin; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + controller.ConfigureActiveTab(settings); + + // Assert + Assert.AreEqual(TabContainer, settings.ActiveTab.ContainerSrc); + } + + [Test] + public void ConfigureTab_Formats_Tab_ContainerSrc_If_Neccessary() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ContainerSrc = GlobalTabContainer }; + settings.ActiveTab = validTab; + settings.ActiveTab.SkinSrc = TabSkin; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + // Act + controller.ConfigureActiveTab(settings); + + // Assert + Assert.AreEqual(SkinController.FormatSkinSrc(GlobalTabContainer, settings), settings.ActiveTab.ContainerSrc); + } + + [Test] + public void ConfigureTab_Builds_Breadcrumbs_For_Tab() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = GlobalTabSkin }; + settings.ActiveTab = validTab; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + this.mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); + + // Act + controller.ConfigureActiveTab(settings); + + // Assert + Assert.NotNull(settings.ActiveTab.BreadCrumbs); + Assert.AreEqual(1, settings.ActiveTab.BreadCrumbs.Count); + } + + [Test] + public void ConfigureTab_Builds_Breadcrumbs_For_Tab_And_Parent() + { + // Arrange + var controller = new PortalSettingsController(); + var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ParentId = ParentTabId }; + var parentTab = new TabInfo { TabID = ParentTabId, PortalID = ValidPortalId }; + settings.ActiveTab = validTab; + settings.ActiveTab.SkinSrc = TabSkin; + + var mockLocaleController = new Mock(); + mockLocaleController.Setup(c => c.GetLocales(It.IsAny())).Returns(new Dictionary()); + LocaleController.RegisterInstance(mockLocaleController.Object); + + var mockTabController = new Mock(); + mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { validTab, parentTab })); + mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); + TabController.SetTestableInstance(mockTabController.Object); + + this.mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); + + // Act + controller.ConfigureActiveTab(settings); + + // Assert + var actualParent = settings.ActiveTab.BreadCrumbs[0] as TabInfo; + var actualTab = settings.ActiveTab.BreadCrumbs[1] as TabInfo; + Assert.AreEqual(2, settings.ActiveTab.BreadCrumbs.Count); + Assert.AreEqual(ValidTabId, actualTab.TabID); + Assert.AreEqual(ParentTabId, actualParent.TabID); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs index 5b917da70d9..1a2dc6d3357 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs @@ -2,72 +2,71 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Providers.Folder +namespace DotNetNuke.Tests.Core.Providers.Folder { using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; - using DotNetNuke.Common.Internal; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Services.FileSystem; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.FileSystem; using DotNetNuke.Tests.Utilities.Mocks; - using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using NUnit.Framework; + using Moq; + using NUnit.Framework; - [TestFixture] - public class FileContentTypeManagerTests - { - [SetUp] - public void Setup() - { - var serviceCollection = new ServiceCollection(); + [TestFixture] + public class FileContentTypeManagerTests + { + [SetUp] + public void Setup() + { + var serviceCollection = new ServiceCollection(); var mockApplicationStatusInfo = new Mock(); mockApplicationStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.Install); serviceCollection.AddTransient(container => mockApplicationStatusInfo.Object); serviceCollection.AddTransient(container => Mock.Of()); - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - - var _mockData = MockComponentProvider.CreateDataProvider(); - var _mockCache = MockComponentProvider.CreateDataCacheProvider(); - var _globals = new Mock(); - var _cbo = new Mock(); - - _mockData.Setup(m => m.GetProviderPath()).Returns(string.Empty); - - TestableGlobals.SetTestableInstance(_globals.Object); - CBO.SetTestableInstance(_cbo.Object); - } - - [TearDown] - public void TearDown() - { - Globals.DependencyProvider = null; - TestableGlobals.ClearInstance(); - CBO.ClearInstance(); - } - - [Test] - public void GetContentType_Returns_Known_Value_When_Extension_Is_Not_Managed() - { - const string notManagedExtension = "asdf609vas21AS:F,l/&%/(%$"; - - var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); - - Assert.AreEqual("application/octet-stream", contentType); - } - - [Test] - public void GetContentType_Returns_Correct_Value_For_Extension() - { - const string notManagedExtension = "htm"; - - var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); - - Assert.AreEqual("text/html", contentType); - } - } -} + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + var _mockData = MockComponentProvider.CreateDataProvider(); + var _mockCache = MockComponentProvider.CreateDataCacheProvider(); + var _globals = new Mock(); + var _cbo = new Mock(); + + _mockData.Setup(m => m.GetProviderPath()).Returns(string.Empty); + + TestableGlobals.SetTestableInstance(_globals.Object); + CBO.SetTestableInstance(_cbo.Object); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + TestableGlobals.ClearInstance(); + CBO.ClearInstance(); + } + + [Test] + public void GetContentType_Returns_Known_Value_When_Extension_Is_Not_Managed() + { + const string notManagedExtension = "asdf609vas21AS:F,l/&%/(%$"; + + var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); + + Assert.AreEqual("application/octet-stream", contentType); + } + + [Test] + public void GetContentType_Returns_Correct_Value_For_Extension() + { + const string notManagedExtension = "htm"; + + var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); + + Assert.AreEqual("text/html", contentType); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs index 71c5b655c57..70c8d21367b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs @@ -2,1125 +2,1136 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Providers.Folder -{ - using System; - using System.Collections.Generic; - using System.Data; - using System.Drawing; - using System.IO; - using System.Reflection; - using System.Text; - - using DotNetNuke.Common.Internal; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Entities.Content; - using DotNetNuke.Entities.Content.Workflow; - using DotNetNuke.Entities.Content.Workflow.Entities; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Security.Permissions; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.FileSystem; - using DotNetNuke.Services.FileSystem.Internal; - using DotNetNuke.Services.Log.EventLog; - using DotNetNuke.Tests.Utilities; - using DotNetNuke.Tests.Utilities.Mocks; - using Moq; - using NUnit.Framework; - - using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - - [TestFixture] - public class FileManagerTests - { - private FileManager _fileManager; - private Mock _folderManager; - private Mock _folderPermissionController; - private Mock _portalController; - private Mock _folderMappingController; - private Mock _globals; - private Mock _cbo; - private Mock _mockData; - private Mock _mockFolder; - private Mock _mockCache; - private Mock _mockFileManager; - private Mock _folderInfo; - private Mock _fileInfo; - private Mock _pathUtils; - private Mock _fileVersionController; - private Mock _workflowManager; - private Mock> _fileEventHandlersContainer; - private Mock _mockFileLockingController; - private Mock _mockFileDeletionController; - private Mock _hostController; - - [SetUp] - public void Setup() - { - this._mockData = MockComponentProvider.CreateDataProvider(); - this._mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); - this._mockCache = MockComponentProvider.CreateDataCacheProvider(); - - this._folderManager = new Mock(); - this._folderPermissionController = new Mock(); - this._portalController = new Mock(); - this._hostController = new Mock(); - this._folderMappingController = new Mock(); - this._fileVersionController = new Mock(); - this._workflowManager = new Mock(); - this._fileEventHandlersContainer = new Mock>(); - this._globals = new Mock(); - this._cbo = new Mock(); - this._pathUtils = new Mock(); - this._mockFileLockingController = new Mock(); - this._mockFileDeletionController = new Mock(); - - EventLogController.SetTestableInstance(Mock.Of()); - FolderManager.RegisterInstance(this._folderManager.Object); - FolderPermissionController.SetTestableInstance(this._folderPermissionController.Object); - PortalController.SetTestableInstance(this._portalController.Object); - HostController.RegisterInstance(this._hostController.Object); - FolderMappingController.RegisterInstance(this._folderMappingController.Object); - TestableGlobals.SetTestableInstance(this._globals.Object); - CBO.SetTestableInstance(this._cbo.Object); - PathUtils.RegisterInstance(this._pathUtils.Object); - FileVersionController.RegisterInstance(this._fileVersionController.Object); - WorkflowManager.SetTestableInstance(this._workflowManager.Object); - EventHandlersContainer.RegisterInstance(this._fileEventHandlersContainer.Object); - this._mockFileManager = new Mock { CallBase = true }; - - this._folderInfo = new Mock(); - this._fileInfo = new Mock(); - - this._fileManager = new FileManager(); - - FileLockingController.SetTestableInstance(this._mockFileLockingController.Object); - FileDeletionController.SetTestableInstance(this._mockFileDeletionController.Object); - } - - [TearDown] - public void TearDown() - { - TestableGlobals.ClearInstance(); - CBO.ClearInstance(); - - FolderPermissionController.ClearInstance(); - FileLockingController.ClearInstance(); - FileDeletionController.ClearInstance(); - MockComponentProvider.ResetContainer(); - PortalController.ClearInstance(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void AddFile_Throws_On_Null_Folder() - { - this._fileManager.AddFile(null, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void AddFile_Throws_On_Null_Or_Empty_FileName(string fileName) - { - this._fileManager.AddFile(this._folderInfo.Object, fileName, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void AddFile_Throws_On_Null_FileContent() - { - this._fileManager.AddFile(this._folderInfo.Object, It.IsAny(), null, It.IsAny(), It.IsAny(), It.IsAny()); - } - - [Test] - [ExpectedException(typeof(PermissionsNotMetException))] - public void AddFile_Throws_When_Permissions_Are_Not_Met() - { - this._folderPermissionController.Setup(fpc => fpc.CanAddFolder(this._folderInfo.Object)).Returns(false); - - this._fileManager.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, new MemoryStream(), It.IsAny(), true, It.IsAny()); - } - - [Test] - [ExpectedException(typeof(NoSpaceAvailableException))] - public void AddFile_Throws_When_Portal_Has_No_Space_Available() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._mockData.Setup(c => c.GetProviderPath()).Returns(string.Empty); - - var fileContent = new MemoryStream(); - - this._globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(false); - - this._mockFileManager.Setup(fm => fm.CreateFileContentItem()).Returns(new ContentItem()); - this._mockFileManager.Setup(fm => fm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); - - this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); - } - - [Test] - public void AddFile_Checks_Space_For_Stream_Length() - { - // Arrange - this.PrepareFileSecurityCheck(); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._folderInfo.Setup(fi => fi.WorkflowID).Returns(Null.NullInteger); - - var fileContent = new MemoryStream(Encoding.ASCII.GetBytes("some data here")); - - this._portalController.Setup(pc => pc.HasSpaceAvailable(It.IsAny(), It.IsAny())).Returns(true); - - this._globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(false); - this._mockFolder.Setup(mf => mf.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)).Verifiable(); - - this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); - this._mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); - this._mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); - - this._workflowManager.Setup(we => we.GetWorkflow(It.IsAny())).Returns((Workflow)null); - - // Act - this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, true, false, Constants.CONTENTTYPE_ValidContentType); - - // Assert - this._portalController.Verify(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)); - } - - [Test] - [ExpectedException(typeof(InvalidFileExtensionException))] - public void AddFile_Throws_When_Extension_Is_Invalid() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - var fileContent = new MemoryStream(); - - this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); - - this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(false); - - this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); - } - - [TestCase("invalid_script.svg")] - [TestCase("invalid_onload.svg")] - [TestCase("invalid_onerror.svg")] - [ExpectedException(typeof(InvalidFileContentException))] - public void AddFile_Throws_When_File_Content_Is_Invalid(string fileName) - { - this.PrepareFileSecurityCheck(); - - using (var fileContent = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Resources\\{fileName}"))) - { - this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); - this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidSvgFileName)).Returns(true); - - this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidSvgFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); - } - } - - [Test] - public void AddFile_No_Error_When_File_Content_Is_Valid() - { - this.PrepareFileSecurityCheck(); - - using (var fileContent = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\valid.svg"))) - { - this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); - this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidSvgFileName)).Returns(true); - this._mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); - - this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidSvgFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); - } - } - - [Test] - public void AddFile_Does_Not_Call_FolderProvider_AddFile_When_Not_Overwritting_And_File_Exists() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._folderInfo.Setup(fi => fi.WorkflowID).Returns(Null.NullInteger); - - var fileContent = new MemoryStream(); - - this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); - - this._globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true); - this._mockFolder.Setup(mf => mf.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)); - this._mockFolder.Setup(mf => mf.GetHashCode(It.IsAny())).Returns("aaa"); - - this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); - this._mockFileManager.Setup(mfm => mfm.UpdateFile(It.IsAny(), It.IsAny())); - this._mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); - - this._workflowManager.Setup(wc => wc.GetWorkflow(It.IsAny())).Returns((Workflow)null); - - this._mockData.Setup( - md => - md.AddFile( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Returns(Constants.FOLDER_ValidFileId); - - this._mockData.Setup(md => md.UpdateFileLastModificationTime(It.IsAny(), It.IsAny())); - - this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); - - this._mockFolder.Verify(mf => mf.AddFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void CopyFile_Throws_On_Null_File() - { - this._fileManager.CopyFile(null, this._folderInfo.Object); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void CopyFile_Throws_On_Null_DestinationFolder() - { - this._fileManager.CopyFile(this._fileInfo.Object, null); - } - - [Test] - public void CopyFile_Calls_FileManager_AddFile_When_FolderMapping_Of_Source_And_Destination_Folders_Are_Not_Equal() - { - const int sourceFolderMappingID = Constants.FOLDER_ValidFolderMappingID; - const int destinationFolderMappingID = Constants.FOLDER_ValidFolderMappingID + 1; - - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - this._fileInfo.Setup(fi => fi.ContentType).Returns(Constants.CONTENTTYPE_ValidContentType); - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(sourceFolderMappingID); - - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(destinationFolderMappingID); - - var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - var fileContent = new MemoryStream(bytes); - - this._mockFileManager.Setup(mfm => mfm.GetFileContent(this._fileInfo.Object)).Returns(fileContent); - this._mockFileManager.Setup(mfm => mfm.CopyContentItem(It.IsAny())).Returns(Constants.CONTENT_ValidContentItemId); - this._mockFileManager.Setup(mfm => mfm.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny(), true, true, Constants.CONTENTTYPE_ValidContentType)); - - this._mockFileManager.Object.CopyFile(this._fileInfo.Object, this._folderInfo.Object); - - this._mockFileManager.Verify(fm => fm.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, true, true, Constants.CONTENTTYPE_ValidContentType), Times.Once()); - } - - [Test] - [ExpectedException(typeof(PermissionsNotMetException))] - public void CopyFile_Throws_When_FolderMapping_Of_Source_And_Destination_Folders_Are_Equal_And_Cannot_Add_Folder() - { - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._folderPermissionController.Setup(fpc => fpc.CanAddFolder(this._folderInfo.Object)).Returns(false); - - this._fileManager.CopyFile(this._fileInfo.Object, this._folderInfo.Object); - } - - [Test] - [ExpectedException(typeof(NoSpaceAvailableException))] - public void CopyFile_Throws_When_FolderMapping_Of_Source_And_Destination_Folders_Are_Equal_And_Portal_Has_No_Space_Available() - { - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._fileInfo.Setup(fi => fi.Size).Returns(Constants.FOLDER_ValidFileSize); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - this._folderPermissionController.Setup(fpc => fpc.CanAddFolder(this._folderInfo.Object)).Returns(true); - this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileSize)).Returns(false); - - this._fileManager.CopyFile(this._fileInfo.Object, this._folderInfo.Object); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void DeleteFile_Throws_On_Null_File() - { - this._fileManager.DeleteFile(null); - } - - [Test] - public void DeleteFile_Calls_FileDeletionControllerDeleteFile() - { - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(this._fileInfo.Object)).Verifiable(); - - this._mockFileManager.Object.DeleteFile(this._fileInfo.Object); - - this._mockFileDeletionController.Verify(); - } - - [Test] - [ExpectedException(typeof(FolderProviderException))] - public void DeleteFile_Throws_WhenFileDeletionControllerThrows() - { - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - - this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(this._fileInfo.Object)) - .Throws(); - - this._mockFileManager.Object.DeleteFile(this._fileInfo.Object); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void DownloadFile_Throws_On_Null_File() - { - this._fileManager.WriteFileToResponse(null, ContentDisposition.Inline); - } - - [Test] - [ExpectedException(typeof(PermissionsNotMetException))] - public void DownloadFile_Throws_When_Permissions_Are_Not_Met() - { - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - - this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - - this._folderPermissionController.Setup(fpc => fpc.CanViewFolder(this._folderInfo.Object)).Returns(false); - - this._fileManager.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); - } - - [Test] - public void DownloadFile_Calls_FileManager_AutoSyncFile_When_File_AutoSync_Is_Enabled() - { - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - - this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - - this._folderPermissionController.Setup(fpc => fpc.CanViewFolder(this._folderInfo.Object)).Returns(true); - - this._mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(true); - this._mockFileManager.Setup(mfm => mfm.AutoSyncFile(this._fileInfo.Object)).Verifiable(); - this._mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this._fileInfo.Object, It.IsAny())); - - this._mockFileManager.Object.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); - - this._mockFileManager.Verify(); - } - - [Test] - public void DownloadFile_Does_Not_Call_FileManager_AutoSyncFile_When_File_AutoSync_Is_Not_Enabled() - { - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - - this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - - this._folderPermissionController.Setup(fpc => fpc.CanViewFolder(this._folderInfo.Object)).Returns(true); - - this._mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(false); - this._mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this._fileInfo.Object, It.IsAny())); - - this._mockFileManager.Object.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); - - this._mockFileManager.Verify(mfm => mfm.AutoSyncFile(this._fileInfo.Object), Times.Never()); - } - - [Test] - public void DownloadFile_Calls_FileManager_WriteBytesToHttpContext() - { - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - - this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - - this._folderPermissionController.Setup(fpc => fpc.CanViewFolder(this._folderInfo.Object)).Returns(true); - - this._mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(false); - this._mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this._fileInfo.Object, It.IsAny())).Verifiable(); - - this._mockFileManager.Object.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); - - this._mockFileManager.Verify(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void ExistsFile_Throws_On_Null_Folder() - { - this._fileManager.FileExists(null, It.IsAny()); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void ExistsFile_Throws_On_Null_Or_Empty_FileName(string fileName) - { - this._fileManager.FileExists(this._folderInfo.Object, fileName); - } - - [Test] - public void ExistsFile_Calls_FileManager_GetFile() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - - this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(null).Verifiable(); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - - this._mockFileManager.Verify(); - } - - [Test] - public void ExistsFile_Calls_FolderProvider_ExistsFile() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this._fileInfo.Object); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true).Verifiable(); - - this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - - this._mockFolder.Verify(); - } - - [Test] - public void ExistsFile_Returns_True_When_File_Exists() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this._fileInfo.Object); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true); - - var result = this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - - Assert.IsTrue(result); - } - - [Test] - public void ExistsFile_Returns_False_When_File_Does_Not_Exist() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this._fileInfo.Object); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(false); - - var result = this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - - Assert.IsFalse(result); - } - - [Test] - [ExpectedException(typeof(FolderProviderException))] - public void ExistsFile_Throws_When_FolderProvider_Throws() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this._fileInfo.Object); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Throws(); - - this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void GetFile_Throws_On_Null_Or_Empty_FileName(string fileName) - { - this._fileManager.GetFile(this._folderInfo.Object, fileName); - } - - [Test] - public void GetFile_Calls_DataProvider_GetFile() - { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - - this._mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); - - this._fileManager.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - - this._mockData.Verify(); - } - - [Test] - public void GetFile_Handles_Path_In_Portal_Root() - { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderManager.Setup(x => x.GetFolder(Constants.CONTENT_ValidPortalId, string.Empty)).Returns(this._folderInfo.Object).Verifiable(); - this._mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); - - this._fileManager.GetFile(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileName); - - this._folderManager.Verify(); - this._mockData.Verify(); - } - - [Test] - public void GetFile_Handles_Path_Beyond_Portal_Root() - { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderManager.Setup(x => x.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object).Verifiable(); - this._mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); - - this._fileManager.GetFile(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath + Constants.FOLDER_ValidFileName); - - this._folderManager.Verify(); - this._mockData.Verify(); - } - - [Test] - public void GetFileByID_Does_Not_Call_DataCache_GetCache_If_FileId_Is_Not_Valid() - { - this._mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(this._fileInfo.Object).Verifiable(); - - this._fileManager.GetFile(Constants.FOLDER_InvalidFileId); - - this._mockCache.Verify(mc => mc.GetItem(It.IsAny()), Times.Never()); - } - - [Test] - public void GetFileByID_Calls_DataCache_GetCache_First() - { - this._mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(this._fileInfo.Object).Verifiable(); - - this._fileManager.GetFile(Constants.FOLDER_ValidFileId); - - this._mockCache.Verify(); - } - - [Test] - public void GetFileByID_Calls_DataProvider_GetFileById_When_File_Is_Not_In_Cache() - { - this._mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(null); - - this._fileManager.GetFile(Constants.FOLDER_ValidFileId); - - this._mockData.Verify(md => md.GetFileById(Constants.FOLDER_ValidFileId, It.IsAny()), Times.Once()); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void MoveFile_Throws_On_Null_File() - { - this._fileManager.MoveFile(null, this._folderInfo.Object); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void MoveFile_Throws_On_Null_DestinationFolder() - { - this._fileManager.MoveFile(this._fileInfo.Object, null); - } - - [Test] - public void MoveFile_Calls_FolderProvider_AddFile_And_DeleteFile_And_FileManager_UpdateFile() - { - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - var fileContent = new MemoryStream(); - - this._mockFileManager.Setup(mfm => mfm.GetFileContent(this._fileInfo.Object)).Returns(fileContent); - string someString; - this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this._fileInfo.Object, out someString)).Returns(false); - this._mockFileManager.Setup(mfm => mfm.MoveVersions(this._fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); - - this._mockFolder.Setup(mf => mf.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)).Verifiable(); - this._mockFolder.Setup(mf => mf.DeleteFile(this._fileInfo.Object)).Verifiable(); - - this._mockFileManager.Setup(mfm => mfm.UpdateFile(this._fileInfo.Object)).Verifiable(); - - this._mockFileManager.Object.MoveFile(this._fileInfo.Object, this._folderInfo.Object); - - this._mockFolder.Verify(); - this._mockFileManager.Verify(); - } - - [Test] - public void MoveFile_Updates_FolderId_And_Folder() - { - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - this._fileInfo.Setup(fi => fi.Folder).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._fileInfo.SetupSet(fi => fi.FolderId = Constants.FOLDER_OtherValidFolderId).Verifiable(); - this._fileInfo.SetupSet(fi => fi.Folder = Constants.FOLDER_OtherValidFolderRelativePath).Verifiable(); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - var fileContent = new MemoryStream(); - - this._mockFileManager.Setup(mfm => mfm.GetFileContent(this._fileInfo.Object)).Returns(fileContent); - string someString; - this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this._fileInfo.Object, out someString)).Returns(false); - this._mockFileManager.Setup(mfm => mfm.MoveVersions(this._fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); - this._mockFileManager.Object.MoveFile(this._fileInfo.Object, this._folderInfo.Object); - - this._fileInfo.Verify(); - } - - [Test] - public void MoveFile_Calls_DeleteFile_When_A_File_With_The_Same_Name_Exists_On_The_Destination_Folder() - { - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - var fileContent = new MemoryStream(); - - this._mockFileManager.Setup(mfm => mfm.GetFileContent(this._fileInfo.Object)).Returns(fileContent); - string someString; - this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this._fileInfo.Object, out someString)).Returns(false); - this._mockFileManager.Setup(mfm => mfm.MoveVersions(this._fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); - - var existingFile = new FileInfo(); - this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(existingFile); - - this._mockFileManager.Setup(mfm => mfm.DeleteFile(existingFile)).Verifiable(); - - this._mockFileManager.Object.MoveFile(this._fileInfo.Object, this._folderInfo.Object); - - this._mockFileManager.Verify(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RenameFile_Throws_On_Null_File() - { - this._fileManager.RenameFile(null, It.IsAny()); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void RenameFile_Throws_On_Null_Or_Empty_NewFileName(string newFileName) - { - this._fileManager.RenameFile(this._fileInfo.Object, newFileName); - } - - [Test] - public void RenameFile_Calls_FolderProvider_RenameFile_When_FileNames_Are_Distinct_And_NewFileName_Does_Not_Exist() - { - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - - this._mockFileManager.Setup(mfm => mfm.FileExists(this._folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(false); - this._mockFileManager.Setup(mfm => mfm.UpdateFile(this._fileInfo.Object)); - this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); - - var folderMapping = new FolderMappingInfo(); - folderMapping.FolderProviderType = Constants.FOLDER_ValidFolderProviderType; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); - - this._mockFolder.Verify(mf => mf.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName), Times.Once()); - } - - [Test] - public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_FileNames_Are_Equal() - { - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - - this._fileManager.RenameFile(this._fileInfo.Object, Constants.FOLDER_ValidFileName); - - this._mockFolder.Verify(mf => mf.RenameFile(this._fileInfo.Object, It.IsAny()), Times.Never()); - } - - [Test] - [ExpectedException(typeof(FileAlreadyExistsException))] - public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_NewFileName_Exists() - { - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - - this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - - this._mockFileManager.Setup(mfm => mfm.FileExists(this._folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(true); - this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); - - this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); - } - - [Test] - [ExpectedException(typeof(InvalidFileExtensionException))] - public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_InvalidExtensionType() - { - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - - this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - this._mockFileManager.Setup(fm => fm.IsAllowedExtension(It.IsAny())).Returns(false); - - this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherInvalidFileNameExtension); - } - - [Test] - [ExpectedException(typeof(FolderProviderException))] - public void RenameFile_Throws_When_FolderProvider_Throws() - { - this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - - this._mockFileManager.Setup(mfm => mfm.FileExists(this._folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(false); - this._mockFileManager.Setup(mfm => mfm.UpdateFile(this._fileInfo.Object)); - this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); - - var folderMapping = new FolderMappingInfo(); - folderMapping.FolderProviderType = Constants.FOLDER_ValidFolderProviderType; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName)).Throws(); - - this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void UnzipFile_Throws_On_Null_File() - { - this._fileManager.UnzipFile(null, It.IsAny()); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void UnzipFile_Throws_On_Null_DestinationFolder() - { - this._fileManager.UnzipFile(It.IsAny(), null); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void UnzipFile_Throws_When_File_Extension_Is_Not_Zip() - { - this._fileInfo.Setup(fi => fi.Extension).Returns("txt"); - - this._fileManager.UnzipFile(this._fileInfo.Object, It.IsAny()); - } - - [Test] - public void UnzipFile_Calls_FileManager_ExtractFiles() - { - this._fileInfo.Setup(fi => fi.Extension).Returns("zip"); - - this._mockFileManager.Setup(mfm => mfm.ExtractFiles(this._fileInfo.Object, this._folderInfo.Object, null)).Verifiable(); - - this._mockFileManager.Object.UnzipFile(this._fileInfo.Object, this._folderInfo.Object); - - this._mockFileManager.Verify(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void UpdateFile_Throws_On_Null_File() - { - this._fileManager.UpdateFile(null); - } - - [Test] - public void UpdateFile_Calls_DataProvider_UpdateFile() - { - this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - this._mockFileManager.Object.UpdateFile(this._fileInfo.Object); - - this._mockData.Verify( - md => md.UpdateFile( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny()), - Times.Once()); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void UpdateFile_Throws_On_Null_File_Overload() - { - this._fileManager.UpdateFile(null, It.IsAny()); - } - - [Test] - public void UpdateFile_Sets_With_And_Height_When_File_Is_Image() - { - var image = new Bitmap(10, 20); - - this._mockFileManager.Setup(mfm => mfm.IsImageFile(this._fileInfo.Object)).Returns(true); - this._mockFileManager.Setup(mfm => mfm.GetImageFromStream(It.IsAny())).Returns(image); - this._mockFileManager.Setup(mfm => mfm.GetHash(this._fileInfo.Object)); - - var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - var stream = new MemoryStream(bytes); - - this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - - this._folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); - this._mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); - - this._mockFileManager.Object.UpdateFile(this._fileInfo.Object, stream); - - this._fileInfo.VerifySet(fi => fi.Width = 10); - this._fileInfo.VerifySet(fi => fi.Height = 20); - } - - [Test] - public void UpdateFile_Sets_SHA1Hash() - { - var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - var stream = new MemoryStream(bytes); - - this._mockFileManager.Setup(mfm => mfm.IsImageFile(this._fileInfo.Object)).Returns(false); - this._mockFileManager.Setup(mfm => mfm.GetHash(stream)).Returns(Constants.FOLDER_UnmodifiedFileHash); - - this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - - this._folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); - this._mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); - - this._mockFileManager.Object.UpdateFile(this._fileInfo.Object, stream); - - this._fileInfo.VerifySet(fi => fi.SHA1Hash = Constants.FOLDER_UnmodifiedFileHash); - } - - [Test] - public void UpdateFile_Calls_FileManager_UpdateFile_Overload() - { - var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - var stream = new MemoryStream(bytes); - - this._mockFileManager.Setup(mfm => mfm.IsImageFile(this._fileInfo.Object)).Returns(false); - this._mockFileManager.Setup(mfm => mfm.GetHash(this._fileInfo.Object)).Returns(Constants.FOLDER_UnmodifiedFileHash); - - this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - - this._folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); - this._mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); - - this._mockFileManager.Object.UpdateFile(this._fileInfo.Object, stream); - - this._mockFileManager.Verify(mfm => mfm.UpdateFile(this._fileInfo.Object), Times.Once()); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void GetSeekableStream_Throws_On_Null_Stream() - { - this._fileManager.GetSeekableStream(null); - } - - [Test] - public void GetSeekableStream_Returns_The_Same_Stream_If_It_Is_Seekable() - { - var inputStream = new MemoryStream(); - var seekableStream = this._fileManager.GetSeekableStream(inputStream); - - Assert.AreEqual(inputStream, seekableStream); - } - - [Test] - public void GetSeekableStream_Calls_GetHostMapPath_And_Creates_A_Temporary_FileStream_With_Resx_Extension() - { - var inputStream = new Mock(); - inputStream.Setup(s => s.CanSeek).Returns(false); - inputStream.Setup(s => s.Read(It.IsAny(), It.IsAny(), It.IsAny())).Returns(0); - - this._mockFileManager.Setup(mfm => mfm.GetHostMapPath()).Returns(string.Empty).Verifiable(); - this._mockFileManager.Setup(mfm => mfm.GetAutoDeleteFileStream(It.Is((string x) => x.EndsWith(".resx")))).Returns(new MemoryStream()).Verifiable(); - - this._mockFileManager.Object.GetSeekableStream(inputStream.Object); - - this._mockFileManager.Verify(); - } - - private void PrepareFileSecurityCheck() - { - this._mockData.Setup(p => p.GetListEntriesByListName("FileSecurityChecker", string.Empty, Null.NullInteger)).Returns(() => - { - var dataTable = new DataTable(); - dataTable.Columns.Add("EntryID", typeof(int)); - dataTable.Columns.Add("ListName", typeof(string)); - dataTable.Columns.Add("Value", typeof(string)); - dataTable.Columns.Add("Text", typeof(string)); - dataTable.Columns.Add("Level", typeof(int)); - dataTable.Columns.Add("SortOrder", typeof(int)); - dataTable.Columns.Add("DefinitionID", typeof(int)); - dataTable.Columns.Add("ParentID", typeof(int)); - dataTable.Columns.Add("Description", typeof(string)); - dataTable.Columns.Add("PortalID", typeof(int)); - dataTable.Columns.Add("SystemList", typeof(bool)); - dataTable.Columns.Add("ParentKey", typeof(string)); - dataTable.Columns.Add("Parent", typeof(string)); - dataTable.Columns.Add("ParentList", typeof(string)); - dataTable.Columns.Add("MaxSortOrder", typeof(int)); - dataTable.Columns.Add("EntryCount", typeof(int)); - dataTable.Columns.Add("HasChildren", typeof(int)); - dataTable.Columns.Add("CreatedByUserID", typeof(int)); - dataTable.Columns.Add("CreatedOnDate", typeof(DateTime)); - dataTable.Columns.Add("LastModifiedByUserID", typeof(int)); - dataTable.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - dataTable.Rows.Add(1, "FileSecurityChecker", "svg", - "DotNetNuke.Services.FileSystem.Internal.SecurityCheckers.SvgFileChecker, DotNetNuke", - 0, 0, -1, -0, string.Empty, -1, 1, string.Empty, string.Empty, string.Empty, 0, 1, 0, -1, DateTime.Now, -1, DateTime.Now); - - return dataTable.CreateDataReader(); - }); - this._hostController.Setup(c => c.GetString("PerformanceSetting")).Returns("NoCaching"); - this._globals.Setup(g => g.HostMapPath).Returns(AppDomain.CurrentDomain.BaseDirectory); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - } - - private class UnSeekableStream : MemoryStream - { - public override bool CanSeek - { - get { return false; } - } - } - } -} +namespace DotNetNuke.Tests.Core.Providers.Folder +{ + using System; + using System.Data; + using System.Drawing; + using System.IO; + using System.Text; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + [TestFixture] + public class FileManagerTests + { + private FileManager fileManager; + private Mock folderManager; + private Mock folderPermissionController; + private Mock portalController; + private Mock folderMappingController; + private Mock globals; + private Mock cbo; + private Mock mockData; + private Mock mockFolder; + private Mock mockCache; + private Mock mockFileManager; + private Mock folderInfo; + private Mock fileInfo; + private Mock pathUtils; + private Mock fileVersionController; + private Mock workflowManager; + private Mock> fileEventHandlersContainer; + private Mock mockFileLockingController; + private Mock mockFileDeletionController; + private Mock hostController; + + [SetUp] + public void Setup() + { + this.mockData = MockComponentProvider.CreateDataProvider(); + this.mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); + this.mockCache = MockComponentProvider.CreateDataCacheProvider(); + + this.folderManager = new Mock(); + this.folderPermissionController = new Mock(); + this.portalController = new Mock(); + this.hostController = new Mock(); + this.hostController.As(); + this.folderMappingController = new Mock(); + this.fileVersionController = new Mock(); + this.workflowManager = new Mock(); + this.fileEventHandlersContainer = new Mock>(); + this.globals = new Mock(); + this.cbo = new Mock(); + this.pathUtils = new Mock(); + this.mockFileLockingController = new Mock(); + this.mockFileDeletionController = new Mock(); + + EventLogController.SetTestableInstance(Mock.Of()); + FolderManager.RegisterInstance(this.folderManager.Object); + FolderPermissionController.SetTestableInstance(this.folderPermissionController.Object); + PortalController.SetTestableInstance(this.portalController.Object); + FolderMappingController.RegisterInstance(this.folderMappingController.Object); + TestableGlobals.SetTestableInstance(this.globals.Object); + CBO.SetTestableInstance(this.cbo.Object); + PathUtils.RegisterInstance(this.pathUtils.Object); + FileVersionController.RegisterInstance(this.fileVersionController.Object); + WorkflowManager.SetTestableInstance(this.workflowManager.Object); + EventHandlersContainer.RegisterInstance(this.fileEventHandlersContainer.Object); + this.mockFileManager = new Mock { CallBase = true }; + + this.folderInfo = new Mock(); + this.fileInfo = new Mock(); + + this.fileManager = new FileManager(); + + FileLockingController.SetTestableInstance(this.mockFileLockingController.Object); + FileDeletionController.SetTestableInstance(this.mockFileDeletionController.Object); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => (IHostSettingsService)this.hostController.Object); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + TestableGlobals.ClearInstance(); + CBO.ClearInstance(); + + FolderPermissionController.ClearInstance(); + FileLockingController.ClearInstance(); + FileDeletionController.ClearInstance(); + MockComponentProvider.ResetContainer(); + PortalController.ClearInstance(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void AddFile_Throws_On_Null_Folder() + { + this.fileManager.AddFile(null, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void AddFile_Throws_On_Null_Or_Empty_FileName(string fileName) + { + this.fileManager.AddFile(this.folderInfo.Object, fileName, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void AddFile_Throws_On_Null_FileContent() + { + this.fileManager.AddFile(this.folderInfo.Object, It.IsAny(), null, It.IsAny(), It.IsAny(), It.IsAny()); + } + + [Test] + [ExpectedException(typeof(PermissionsNotMetException))] + public void AddFile_Throws_When_Permissions_Are_Not_Met() + { + this.folderPermissionController.Setup(fpc => fpc.CanAddFolder(this.folderInfo.Object)).Returns(false); + + this.fileManager.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, new MemoryStream(), It.IsAny(), true, It.IsAny()); + } + + [Test] + [ExpectedException(typeof(NoSpaceAvailableException))] + public void AddFile_Throws_When_Portal_Has_No_Space_Available() + { + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this.folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.mockData.Setup(c => c.GetProviderPath()).Returns(string.Empty); + + var fileContent = new MemoryStream(); + + this.globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(false); + + this.mockFileManager.Setup(fm => fm.CreateFileContentItem()).Returns(new ContentItem()); + this.mockFileManager.Setup(fm => fm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); + + this.mockFileManager.Object.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + } + + [Test] + public void AddFile_Checks_Space_For_Stream_Length() + { + // Arrange + this.PrepareFileSecurityCheck(); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.WorkflowID).Returns(Null.NullInteger); + + var fileContent = new MemoryStream(Encoding.ASCII.GetBytes("some data here")); + + this.portalController.Setup(pc => pc.HasSpaceAvailable(It.IsAny(), It.IsAny())).Returns(true); + + this.globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFolder.Setup(mf => mf.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(false); + this.mockFolder.Setup(mf => mf.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)).Verifiable(); + + this.mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); + this.mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); + this.mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); + + this.workflowManager.Setup(we => we.GetWorkflow(It.IsAny())).Returns((Workflow)null); + + // Act + this.mockFileManager.Object.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, true, false, Constants.CONTENTTYPE_ValidContentType); + + // Assert + this.portalController.Verify(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)); + } + + [Test] + [ExpectedException(typeof(InvalidFileExtensionException))] + public void AddFile_Throws_When_Extension_Is_Invalid() + { + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + var fileContent = new MemoryStream(); + + this.portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); + + this.mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(false); + + this.mockFileManager.Object.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + } + + [TestCase("invalid_script.svg")] + [TestCase("invalid_onload.svg")] + [TestCase("invalid_onerror.svg")] + [ExpectedException(typeof(InvalidFileContentException))] + public void AddFile_Throws_When_File_Content_Is_Invalid(string fileName) + { + this.PrepareFileSecurityCheck(); + + using (var fileContent = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Resources\\{fileName}"))) + { + this.portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); + this.mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidSvgFileName)).Returns(true); + + this.mockFileManager.Object.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidSvgFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + } + } + + [Test] + public void AddFile_No_Error_When_File_Content_Is_Valid() + { + this.PrepareFileSecurityCheck(); + + using (var fileContent = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\valid.svg"))) + { + this.portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); + this.mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidSvgFileName)).Returns(true); + this.mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); + + this.mockFileManager.Object.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidSvgFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + } + } + + [Test] + public void AddFile_Does_Not_Call_FolderProvider_AddFile_When_Not_Overwritting_And_File_Exists() + { + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.WorkflowID).Returns(Null.NullInteger); + + var fileContent = new MemoryStream(); + + this.portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); + + this.globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFolder.Setup(mf => mf.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true); + this.mockFolder.Setup(mf => mf.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)); + this.mockFolder.Setup(mf => mf.GetHashCode(It.IsAny())).Returns("aaa"); + + this.mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); + this.mockFileManager.Setup(mfm => mfm.UpdateFile(It.IsAny(), It.IsAny())); + this.mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); + + this.workflowManager.Setup(wc => wc.GetWorkflow(It.IsAny())).Returns((Workflow)null); + + this.mockData.Setup( + md => + md.AddFile( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Returns(Constants.FOLDER_ValidFileId); + + this.mockData.Setup(md => md.UpdateFileLastModificationTime(It.IsAny(), It.IsAny())); + + this.mockFileManager.Object.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + + this.mockFolder.Verify(mf => mf.AddFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void CopyFile_Throws_On_Null_File() + { + this.fileManager.CopyFile(null, this.folderInfo.Object); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void CopyFile_Throws_On_Null_DestinationFolder() + { + this.fileManager.CopyFile(this.fileInfo.Object, null); + } + + [Test] + public void CopyFile_Calls_FileManager_AddFile_When_FolderMapping_Of_Source_And_Destination_Folders_Are_Not_Equal() + { + const int sourceFolderMappingID = Constants.FOLDER_ValidFolderMappingID; + const int destinationFolderMappingID = Constants.FOLDER_ValidFolderMappingID + 1; + + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this.fileInfo.Setup(fi => fi.ContentType).Returns(Constants.CONTENTTYPE_ValidContentType); + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(sourceFolderMappingID); + + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(destinationFolderMappingID); + + var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + var fileContent = new MemoryStream(bytes); + + this.mockFileManager.Setup(mfm => mfm.GetFileContent(this.fileInfo.Object)).Returns(fileContent); + this.mockFileManager.Setup(mfm => mfm.CopyContentItem(It.IsAny())).Returns(Constants.CONTENT_ValidContentItemId); + this.mockFileManager.Setup(mfm => mfm.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny(), true, true, Constants.CONTENTTYPE_ValidContentType)); + + this.mockFileManager.Object.CopyFile(this.fileInfo.Object, this.folderInfo.Object); + + this.mockFileManager.Verify(fm => fm.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, true, true, Constants.CONTENTTYPE_ValidContentType), Times.Once()); + } + + [Test] + [ExpectedException(typeof(PermissionsNotMetException))] + public void CopyFile_Throws_When_FolderMapping_Of_Source_And_Destination_Folders_Are_Equal_And_Cannot_Add_Folder() + { + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.folderPermissionController.Setup(fpc => fpc.CanAddFolder(this.folderInfo.Object)).Returns(false); + + this.fileManager.CopyFile(this.fileInfo.Object, this.folderInfo.Object); + } + + [Test] + [ExpectedException(typeof(NoSpaceAvailableException))] + public void CopyFile_Throws_When_FolderMapping_Of_Source_And_Destination_Folders_Are_Equal_And_Portal_Has_No_Space_Available() + { + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.fileInfo.Setup(fi => fi.Size).Returns(Constants.FOLDER_ValidFileSize); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + this.folderPermissionController.Setup(fpc => fpc.CanAddFolder(this.folderInfo.Object)).Returns(true); + this.portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileSize)).Returns(false); + + this.fileManager.CopyFile(this.fileInfo.Object, this.folderInfo.Object); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void DeleteFile_Throws_On_Null_File() + { + this.fileManager.DeleteFile(null); + } + + [Test] + public void DeleteFile_Calls_FileDeletionControllerDeleteFile() + { + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(this.fileInfo.Object)).Verifiable(); + + this.mockFileManager.Object.DeleteFile(this.fileInfo.Object); + + this.mockFileDeletionController.Verify(); + } + + [Test] + [ExpectedException(typeof(FolderProviderException))] + public void DeleteFile_Throws_WhenFileDeletionControllerThrows() + { + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + + this.mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(this.fileInfo.Object)) + .Throws(); + + this.mockFileManager.Object.DeleteFile(this.fileInfo.Object); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void DownloadFile_Throws_On_Null_File() + { + this.fileManager.WriteFileToResponse(null, ContentDisposition.Inline); + } + + [Test] + [ExpectedException(typeof(PermissionsNotMetException))] + public void DownloadFile_Throws_When_Permissions_Are_Not_Met() + { + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + + this.folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this.folderInfo.Object); + + this.folderPermissionController.Setup(fpc => fpc.CanViewFolder(this.folderInfo.Object)).Returns(false); + + this.fileManager.WriteFileToResponse(this.fileInfo.Object, ContentDisposition.Inline); + } + + [Test] + public void DownloadFile_Calls_FileManager_AutoSyncFile_When_File_AutoSync_Is_Enabled() + { + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + + this.folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this.folderInfo.Object); + + this.folderPermissionController.Setup(fpc => fpc.CanViewFolder(this.folderInfo.Object)).Returns(true); + + this.mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(true); + this.mockFileManager.Setup(mfm => mfm.AutoSyncFile(this.fileInfo.Object)).Verifiable(); + this.mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this.fileInfo.Object, It.IsAny())); + + this.mockFileManager.Object.WriteFileToResponse(this.fileInfo.Object, ContentDisposition.Inline); + + this.mockFileManager.Verify(); + } + + [Test] + public void DownloadFile_Does_Not_Call_FileManager_AutoSyncFile_When_File_AutoSync_Is_Not_Enabled() + { + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + + this.folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this.folderInfo.Object); + + this.folderPermissionController.Setup(fpc => fpc.CanViewFolder(this.folderInfo.Object)).Returns(true); + + this.mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(false); + this.mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this.fileInfo.Object, It.IsAny())); + + this.mockFileManager.Object.WriteFileToResponse(this.fileInfo.Object, ContentDisposition.Inline); + + this.mockFileManager.Verify(mfm => mfm.AutoSyncFile(this.fileInfo.Object), Times.Never()); + } + + [Test] + public void DownloadFile_Calls_FileManager_WriteBytesToHttpContext() + { + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + + this.folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this.folderInfo.Object); + + this.folderPermissionController.Setup(fpc => fpc.CanViewFolder(this.folderInfo.Object)).Returns(true); + + this.mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(false); + this.mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this.fileInfo.Object, It.IsAny())).Verifiable(); + + this.mockFileManager.Object.WriteFileToResponse(this.fileInfo.Object, ContentDisposition.Inline); + + this.mockFileManager.Verify(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void ExistsFile_Throws_On_Null_Folder() + { + this.fileManager.FileExists(null, It.IsAny()); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void ExistsFile_Throws_On_Null_Or_Empty_FileName(string fileName) + { + this.fileManager.FileExists(this.folderInfo.Object, fileName); + } + + [Test] + public void ExistsFile_Calls_FileManager_GetFile() + { + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + + this.mockFileManager.Setup(mfm => mfm.GetFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(null).Verifiable(); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFileManager.Object.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName); + + this.mockFileManager.Verify(); + } + + [Test] + public void ExistsFile_Calls_FolderProvider_ExistsFile() + { + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.mockFileManager.Setup(mfm => mfm.GetFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this.fileInfo.Object); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFolder.Setup(mf => mf.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true).Verifiable(); + + this.mockFileManager.Object.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName); + + this.mockFolder.Verify(); + } + + [Test] + public void ExistsFile_Returns_True_When_File_Exists() + { + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.mockFileManager.Setup(mfm => mfm.GetFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this.fileInfo.Object); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFolder.Setup(mf => mf.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true); + + var result = this.mockFileManager.Object.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName); + + Assert.IsTrue(result); + } + + [Test] + public void ExistsFile_Returns_False_When_File_Does_Not_Exist() + { + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.mockFileManager.Setup(mfm => mfm.GetFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this.fileInfo.Object); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFolder.Setup(mf => mf.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(false); + + var result = this.mockFileManager.Object.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName); + + Assert.IsFalse(result); + } + + [Test] + [ExpectedException(typeof(FolderProviderException))] + public void ExistsFile_Throws_When_FolderProvider_Throws() + { + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.mockFileManager.Setup(mfm => mfm.GetFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this.fileInfo.Object); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFolder.Setup(mf => mf.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName)).Throws(); + + this.mockFileManager.Object.FileExists(this.folderInfo.Object, Constants.FOLDER_ValidFileName); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void GetFile_Throws_On_Null_Or_Empty_FileName(string fileName) + { + this.fileManager.GetFile(this.folderInfo.Object, fileName); + } + + [Test] + public void GetFile_Calls_DataProvider_GetFile() + { + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + + this.mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); + + this.fileManager.GetFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName); + + this.mockData.Verify(); + } + + [Test] + public void GetFile_Handles_Path_In_Portal_Root() + { + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderManager.Setup(x => x.GetFolder(Constants.CONTENT_ValidPortalId, string.Empty)).Returns(this.folderInfo.Object).Verifiable(); + this.mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); + + this.fileManager.GetFile(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileName); + + this.folderManager.Verify(); + this.mockData.Verify(); + } + + [Test] + public void GetFile_Handles_Path_Beyond_Portal_Root() + { + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderManager.Setup(x => x.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this.folderInfo.Object).Verifiable(); + this.mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); + + this.fileManager.GetFile(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath + Constants.FOLDER_ValidFileName); + + this.folderManager.Verify(); + this.mockData.Verify(); + } + + [Test] + public void GetFileByID_Does_Not_Call_DataCache_GetCache_If_FileId_Is_Not_Valid() + { + this.mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(this.fileInfo.Object).Verifiable(); + + this.fileManager.GetFile(Constants.FOLDER_InvalidFileId); + + this.mockCache.Verify(mc => mc.GetItem(It.IsAny()), Times.Never()); + } + + [Test] + public void GetFileByID_Calls_DataCache_GetCache_First() + { + this.mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(this.fileInfo.Object).Verifiable(); + + this.fileManager.GetFile(Constants.FOLDER_ValidFileId); + + this.mockCache.Verify(); + } + + [Test] + public void GetFileByID_Calls_DataProvider_GetFileById_When_File_Is_Not_In_Cache() + { + this.mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(null); + + this.fileManager.GetFile(Constants.FOLDER_ValidFileId); + + this.mockData.Verify(md => md.GetFileById(Constants.FOLDER_ValidFileId, It.IsAny()), Times.Once()); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void MoveFile_Throws_On_Null_File() + { + this.fileManager.MoveFile(null, this.folderInfo.Object); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void MoveFile_Throws_On_Null_DestinationFolder() + { + this.fileManager.MoveFile(this.fileInfo.Object, null); + } + + [Test] + public void MoveFile_Calls_FolderProvider_AddFile_And_DeleteFile_And_FileManager_UpdateFile() + { + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + var fileContent = new MemoryStream(); + + this.mockFileManager.Setup(mfm => mfm.GetFileContent(this.fileInfo.Object)).Returns(fileContent); + string someString; + this.mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this.fileInfo.Object, out someString)).Returns(false); + this.mockFileManager.Setup(mfm => mfm.MoveVersions(this.fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); + + this.mockFolder.Setup(mf => mf.AddFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)).Verifiable(); + this.mockFolder.Setup(mf => mf.DeleteFile(this.fileInfo.Object)).Verifiable(); + + this.mockFileManager.Setup(mfm => mfm.UpdateFile(this.fileInfo.Object)).Verifiable(); + + this.mockFileManager.Object.MoveFile(this.fileInfo.Object, this.folderInfo.Object); + + this.mockFolder.Verify(); + this.mockFileManager.Verify(); + } + + [Test] + public void MoveFile_Updates_FolderId_And_Folder() + { + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this.fileInfo.Setup(fi => fi.Folder).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.fileInfo.SetupSet(fi => fi.FolderId = Constants.FOLDER_OtherValidFolderId).Verifiable(); + this.fileInfo.SetupSet(fi => fi.Folder = Constants.FOLDER_OtherValidFolderRelativePath).Verifiable(); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + var fileContent = new MemoryStream(); + + this.mockFileManager.Setup(mfm => mfm.GetFileContent(this.fileInfo.Object)).Returns(fileContent); + string someString; + this.mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this.fileInfo.Object, out someString)).Returns(false); + this.mockFileManager.Setup(mfm => mfm.MoveVersions(this.fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); + this.mockFileManager.Object.MoveFile(this.fileInfo.Object, this.folderInfo.Object); + + this.fileInfo.Verify(); + } + + [Test] + public void MoveFile_Calls_DeleteFile_When_A_File_With_The_Same_Name_Exists_On_The_Destination_Folder() + { + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this.fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + var fileContent = new MemoryStream(); + + this.mockFileManager.Setup(mfm => mfm.GetFileContent(this.fileInfo.Object)).Returns(fileContent); + string someString; + this.mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this.fileInfo.Object, out someString)).Returns(false); + this.mockFileManager.Setup(mfm => mfm.MoveVersions(this.fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); + + var existingFile = new FileInfo(); + this.mockFileManager.Setup(mfm => mfm.GetFile(this.folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(existingFile); + + this.mockFileManager.Setup(mfm => mfm.DeleteFile(existingFile)).Verifiable(); + + this.mockFileManager.Object.MoveFile(this.fileInfo.Object, this.folderInfo.Object); + + this.mockFileManager.Verify(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RenameFile_Throws_On_Null_File() + { + this.fileManager.RenameFile(null, It.IsAny()); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void RenameFile_Throws_On_Null_Or_Empty_NewFileName(string newFileName) + { + this.fileManager.RenameFile(this.fileInfo.Object, newFileName); + } + + [Test] + public void RenameFile_Calls_FolderProvider_RenameFile_When_FileNames_Are_Distinct_And_NewFileName_Does_Not_Exist() + { + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this.folderInfo.Object); + + this.mockFileManager.Setup(mfm => mfm.FileExists(this.folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(false); + this.mockFileManager.Setup(mfm => mfm.UpdateFile(this.fileInfo.Object)); + this.mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); + + var folderMapping = new FolderMappingInfo(); + folderMapping.FolderProviderType = Constants.FOLDER_ValidFolderProviderType; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFileManager.Object.RenameFile(this.fileInfo.Object, Constants.FOLDER_OtherValidFileName); + + this.mockFolder.Verify(mf => mf.RenameFile(this.fileInfo.Object, Constants.FOLDER_OtherValidFileName), Times.Once()); + } + + [Test] + public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_FileNames_Are_Equal() + { + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + + this.fileManager.RenameFile(this.fileInfo.Object, Constants.FOLDER_ValidFileName); + + this.mockFolder.Verify(mf => mf.RenameFile(this.fileInfo.Object, It.IsAny()), Times.Never()); + } + + [Test] + [ExpectedException(typeof(FileAlreadyExistsException))] + public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_NewFileName_Exists() + { + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + + this.folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this.folderInfo.Object); + + this.mockFileManager.Setup(mfm => mfm.FileExists(this.folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(true); + this.mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); + + this.mockFileManager.Object.RenameFile(this.fileInfo.Object, Constants.FOLDER_OtherValidFileName); + } + + [Test] + [ExpectedException(typeof(InvalidFileExtensionException))] + public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_InvalidExtensionType() + { + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + + this.folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this.folderInfo.Object); + this.mockFileManager.Setup(fm => fm.IsAllowedExtension(It.IsAny())).Returns(false); + + this.mockFileManager.Object.RenameFile(this.fileInfo.Object, Constants.FOLDER_OtherInvalidFileNameExtension); + } + + [Test] + [ExpectedException(typeof(FolderProviderException))] + public void RenameFile_Throws_When_FolderProvider_Throws() + { + this.fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this.fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this.fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this.fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + this.folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this.folderInfo.Object); + + this.mockFileManager.Setup(mfm => mfm.FileExists(this.folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(false); + this.mockFileManager.Setup(mfm => mfm.UpdateFile(this.fileInfo.Object)); + this.mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); + + var folderMapping = new FolderMappingInfo(); + folderMapping.FolderProviderType = Constants.FOLDER_ValidFolderProviderType; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.mockFolder.Setup(mf => mf.RenameFile(this.fileInfo.Object, Constants.FOLDER_OtherValidFileName)).Throws(); + + this.mockFileManager.Object.RenameFile(this.fileInfo.Object, Constants.FOLDER_OtherValidFileName); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void UnzipFile_Throws_On_Null_File() + { + this.fileManager.UnzipFile(null, It.IsAny()); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void UnzipFile_Throws_On_Null_DestinationFolder() + { + this.fileManager.UnzipFile(It.IsAny(), null); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void UnzipFile_Throws_When_File_Extension_Is_Not_Zip() + { + this.fileInfo.Setup(fi => fi.Extension).Returns("txt"); + + this.fileManager.UnzipFile(this.fileInfo.Object, It.IsAny()); + } + + [Test] + public void UnzipFile_Calls_FileManager_ExtractFiles() + { + this.fileInfo.Setup(fi => fi.Extension).Returns("zip"); + + this.mockFileManager.Setup(mfm => mfm.ExtractFiles(this.fileInfo.Object, this.folderInfo.Object, null)).Verifiable(); + + this.mockFileManager.Object.UnzipFile(this.fileInfo.Object, this.folderInfo.Object); + + this.mockFileManager.Verify(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void UpdateFile_Throws_On_Null_File() + { + this.fileManager.UpdateFile(null); + } + + [Test] + public void UpdateFile_Calls_DataProvider_UpdateFile() + { + this.fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + this.mockFileManager.Object.UpdateFile(this.fileInfo.Object); + + this.mockData.Verify( + md => md.UpdateFile( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Once()); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void UpdateFile_Throws_On_Null_File_Overload() + { + this.fileManager.UpdateFile(null, It.IsAny()); + } + + [Test] + public void UpdateFile_Sets_With_And_Height_When_File_Is_Image() + { + var image = new Bitmap(10, 20); + + this.mockFileManager.Setup(mfm => mfm.IsImageFile(this.fileInfo.Object)).Returns(true); + this.mockFileManager.Setup(mfm => mfm.GetImageFromStream(It.IsAny())).Returns(image); + this.mockFileManager.Setup(mfm => mfm.GetHash(this.fileInfo.Object)); + + var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + var stream = new MemoryStream(bytes); + + this.fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + + this.folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); + this.mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); + + this.mockFileManager.Object.UpdateFile(this.fileInfo.Object, stream); + + this.fileInfo.VerifySet(fi => fi.Width = 10); + this.fileInfo.VerifySet(fi => fi.Height = 20); + } + + [Test] + public void UpdateFile_Sets_SHA1Hash() + { + var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + var stream = new MemoryStream(bytes); + + this.mockFileManager.Setup(mfm => mfm.IsImageFile(this.fileInfo.Object)).Returns(false); + this.mockFileManager.Setup(mfm => mfm.GetHash(stream)).Returns(Constants.FOLDER_UnmodifiedFileHash); + + this.fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + + this.folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); + this.mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); + + this.mockFileManager.Object.UpdateFile(this.fileInfo.Object, stream); + + this.fileInfo.VerifySet(fi => fi.SHA1Hash = Constants.FOLDER_UnmodifiedFileHash); + } + + [Test] + public void UpdateFile_Calls_FileManager_UpdateFile_Overload() + { + var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + var stream = new MemoryStream(bytes); + + this.mockFileManager.Setup(mfm => mfm.IsImageFile(this.fileInfo.Object)).Returns(false); + this.mockFileManager.Setup(mfm => mfm.GetHash(this.fileInfo.Object)).Returns(Constants.FOLDER_UnmodifiedFileHash); + + this.fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + + this.folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); + this.mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); + + this.mockFileManager.Object.UpdateFile(this.fileInfo.Object, stream); + + this.mockFileManager.Verify(mfm => mfm.UpdateFile(this.fileInfo.Object), Times.Once()); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void GetSeekableStream_Throws_On_Null_Stream() + { + this.fileManager.GetSeekableStream(null); + } + + [Test] + public void GetSeekableStream_Returns_The_Same_Stream_If_It_Is_Seekable() + { + var inputStream = new MemoryStream(); + var seekableStream = this.fileManager.GetSeekableStream(inputStream); + + Assert.AreEqual(inputStream, seekableStream); + } + + [Test] + public void GetSeekableStream_Calls_GetHostMapPath_And_Creates_A_Temporary_FileStream_With_Resx_Extension() + { + var inputStream = new Mock(); + inputStream.Setup(s => s.CanSeek).Returns(false); + inputStream.Setup(s => s.Read(It.IsAny(), It.IsAny(), It.IsAny())).Returns(0); + + this.mockFileManager.Setup(mfm => mfm.GetHostMapPath()).Returns(string.Empty).Verifiable(); + this.mockFileManager.Setup(mfm => mfm.GetAutoDeleteFileStream(It.Is((string x) => x.EndsWith(".resx")))).Returns(new MemoryStream()).Verifiable(); + + this.mockFileManager.Object.GetSeekableStream(inputStream.Object); + + this.mockFileManager.Verify(); + } + + private void PrepareFileSecurityCheck() + { + this.mockData.Setup(p => p.GetListEntriesByListName("FileSecurityChecker", string.Empty, Null.NullInteger)).Returns(() => + { + var dataTable = new DataTable(); + dataTable.Columns.Add("EntryID", typeof(int)); + dataTable.Columns.Add("ListName", typeof(string)); + dataTable.Columns.Add("Value", typeof(string)); + dataTable.Columns.Add("Text", typeof(string)); + dataTable.Columns.Add("Level", typeof(int)); + dataTable.Columns.Add("SortOrder", typeof(int)); + dataTable.Columns.Add("DefinitionID", typeof(int)); + dataTable.Columns.Add("ParentID", typeof(int)); + dataTable.Columns.Add("Description", typeof(string)); + dataTable.Columns.Add("PortalID", typeof(int)); + dataTable.Columns.Add("SystemList", typeof(bool)); + dataTable.Columns.Add("ParentKey", typeof(string)); + dataTable.Columns.Add("Parent", typeof(string)); + dataTable.Columns.Add("ParentList", typeof(string)); + dataTable.Columns.Add("MaxSortOrder", typeof(int)); + dataTable.Columns.Add("EntryCount", typeof(int)); + dataTable.Columns.Add("HasChildren", typeof(int)); + dataTable.Columns.Add("CreatedByUserID", typeof(int)); + dataTable.Columns.Add("CreatedOnDate", typeof(DateTime)); + dataTable.Columns.Add("LastModifiedByUserID", typeof(int)); + dataTable.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + + dataTable.Rows.Add(1, "FileSecurityChecker", "svg", + "DotNetNuke.Services.FileSystem.Internal.SecurityCheckers.SvgFileChecker, DotNetNuke", + 0, 0, -1, -0, string.Empty, -1, 1, string.Empty, string.Empty, string.Empty, 0, 1, 0, -1, DateTime.Now, -1, DateTime.Now); + + return dataTable.CreateDataReader(); + }); + this.hostController.Setup(c => c.GetString("PerformanceSetting")).Returns("NoCaching"); + this.globals.Setup(g => g.HostMapPath).Returns(AppDomain.CurrentDomain.BaseDirectory); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + } + + private class UnSeekableStream : MemoryStream + { + public override bool CanSeek + { + get { return false; } + } + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs index 5056140ebe1..b295473477b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs @@ -2,73 +2,84 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Providers.Folder -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Data; - using System.IO; - using System.Linq; - using System.Web.Caching; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.FileSystem; - using DotNetNuke.Services.FileSystem.Internal; - using DotNetNuke.Services.Log.EventLog; - using DotNetNuke.Tests.Core.Providers.Builders; - using DotNetNuke.Tests.Utilities; - using DotNetNuke.Tests.Utilities.Mocks; - using Moq; - using NUnit.Framework; - - using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - - [TestFixture] - public class FolderManagerTests +namespace DotNetNuke.Tests.Core.Providers.Folder +{ + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Tests.Core.Providers.Builders; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + + [TestFixture] + public class FolderManagerTests { - private FolderManager _folderManager; - private Mock _mockFolder; - private Mock _mockData; - private Mock _mockFolderManager; - private Mock _folderInfo; - private Mock _folderMappingController; - private Mock _directory; - private Mock _file; - private Mock _cbo; - private Mock _pathUtils; - private Mock _mockUserSecurityController; - private Mock _mockFileDeletionController; + private FolderManager folderManager; + private Mock mockFolder; + private Mock mockData; + private Mock mockFolderManager; + private Mock folderInfo; + private Mock folderMappingController; + private Mock directory; + private Mock file; + private Mock cbo; + private Mock pathUtils; + private Mock mockUserSecurityController; + private Mock mockFileDeletionController; [SetUp] public void Setup() { - this._mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); - this._mockData = MockComponentProvider.CreateDataProvider(); + this.mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); + this.mockData = MockComponentProvider.CreateDataProvider(); - this._folderMappingController = new Mock(); - this._directory = new Mock(); - this._file = new Mock(); - this._cbo = new Mock(); - this._pathUtils = new Mock(); - this._mockUserSecurityController = new Mock(); - this._mockFileDeletionController = new Mock(); + this.folderMappingController = new Mock(); + this.directory = new Mock(); + this.file = new Mock(); + this.cbo = new Mock(); + this.pathUtils = new Mock(); + this.mockUserSecurityController = new Mock(); + this.mockFileDeletionController = new Mock(); - FolderMappingController.RegisterInstance(this._folderMappingController.Object); - DirectoryWrapper.RegisterInstance(this._directory.Object); - FileWrapper.RegisterInstance(this._file.Object); - CBO.SetTestableInstance(this._cbo.Object); - PathUtils.RegisterInstance(this._pathUtils.Object); - UserSecurityController.SetTestableInstance(this._mockUserSecurityController.Object); - FileDeletionController.SetTestableInstance(this._mockFileDeletionController.Object); + FolderMappingController.RegisterInstance(this.folderMappingController.Object); + DirectoryWrapper.RegisterInstance(this.directory.Object); + FileWrapper.RegisterInstance(this.file.Object); + CBO.SetTestableInstance(this.cbo.Object); + PathUtils.RegisterInstance(this.pathUtils.Object); + UserSecurityController.SetTestableInstance(this.mockUserSecurityController.Object); + FileDeletionController.SetTestableInstance(this.mockFileDeletionController.Object); - this._mockFolderManager = new Mock { CallBase = true }; + this.mockFolderManager = new Mock { CallBase = true }; - this._folderManager = new FolderManager(); + this.folderManager = new FolderManager(); - this._folderInfo = new Mock(); + this.folderInfo = new Mock(); + + var serviceCollection = new ServiceCollection(); + var mockStatusInfo = new Mock(); + mockStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.None); + + serviceCollection.AddTransient(container => mockStatusInfo.Object); + serviceCollection.AddTransient(container => Mock.Of()); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); } [TearDown] @@ -80,13 +91,14 @@ public void TearDown() CBO.ClearInstance(); FileDeletionController.ClearInstance(); MockComponentProvider.ResetContainer(); + Globals.DependencyProvider = null; } [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFolder_Throws_On_Null_FolderPath() { - this._folderManager.AddFolder(It.IsAny(), null); + this.folderManager.AddFolder(It.IsAny(), null); } // [Test] @@ -166,9 +178,9 @@ public void AddFolder_Throws_When_Folder_Already_Exists() PortalID = Constants.CONTENT_ValidPortalId, }; - this._mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(true); + this.mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(true); - this._mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + this.mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); } [Test] @@ -181,16 +193,16 @@ public void AddFolder_Throws_When_FolderPath_Is_Invalid() PortalID = Constants.CONTENT_ValidPortalId, }; - this._mockFolderManager + this.mockFolderManager .Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())) .Returns(false); - this._mockFolderManager + this.mockFolderManager .Setup(mfm => mfm.IsValidFolderPath(It.IsAny())) .Returns(false); // act - this._mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + this.mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); // assert (implicit) } @@ -201,7 +213,7 @@ public void IsValidFolderPath_Returns_True_When_FolderPath_Is_Valid() // arrange (implicit) // act - var result = this._mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_ValidSubFolderRelativePath); + var result = this.mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_ValidSubFolderRelativePath); // assert Assert.IsTrue(result); @@ -213,7 +225,7 @@ public void IsValidFolderPath_Returns_False_When_FolderPath_Is_Invalid() // arrange (implicit) // act - var result = this._mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_InvalidSubFolderRelativePath); + var result = this.mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_InvalidSubFolderRelativePath); // assert Assert.IsFalse(result); @@ -223,7 +235,7 @@ public void IsValidFolderPath_Returns_False_When_FolderPath_Is_Invalid() [ExpectedException(typeof(ArgumentNullException))] public void DeleteFolder_Throws_On_Null_Folder() { - this._folderManager.DeleteFolder(null); + this.folderManager.DeleteFolder(null); } [Test] @@ -232,11 +244,11 @@ public void DeleteFolder_Throws_OnNullFolder_WhenRecursive() { // Arrange var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); // Act var notDeletedSubfolders = new List(); - this._folderManager.DeleteFolder(null, notDeletedSubfolders); + this.folderManager.DeleteFolder(null, notDeletedSubfolders); } [Test] @@ -248,23 +260,23 @@ public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive() .Build(); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); + this.mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(new List()); - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(folderInfo, "DELETE")).Returns(true); + this.mockUserSecurityController.Setup(musc => musc.HasFolderPermission(folderInfo, "DELETE")).Returns(true); // Act var subfoldersNotDeleted = new List(); - this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + this.mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); // Assert - this._mockFolder.Verify(); + this.mockFolder.Verify(); Assert.AreEqual(0, subfoldersNotDeleted.Count); } @@ -292,27 +304,27 @@ public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive_WhenExist }; var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); - this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)).Verifiable(); - this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder2)).Verifiable(); + this.mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); + this.mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)).Verifiable(); + this.mockFolder.Setup(mf => mf.DeleteFolder(subfolder2)).Verifiable(); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); + this.mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); // Act var subfoldersNotDeleted = new List(); - this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + this.mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); // Assert - this._mockFolder.Verify(); + this.mockFolder.Verify(); Assert.AreEqual(0, subfoldersNotDeleted.Count); } @@ -340,23 +352,23 @@ public void DeleteFolder_SubFoldersCollectionIsNotEmpty_WhenRecursive_WhenUserHa }; var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)); + this.mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(subfolder2, "DELETE")).Returns(false); - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsNotIn(subfolder2), "DELETE")).Returns(true); + this.mockUserSecurityController.Setup(musc => musc.HasFolderPermission(subfolder2, "DELETE")).Returns(false); + this.mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsNotIn(subfolder2), "DELETE")).Returns(true); // Act var subfoldersNotDeleted = new List(); - this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + this.mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); // Assert Assert.AreEqual(2, subfoldersNotDeleted.Count); // folderInfo and subfolder2 are not deleted @@ -385,128 +397,128 @@ public void DeleteFolder_Throws_OnFileDeletionControllerThrows_WhenRecursive_Whe }; var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); // _mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(files); + this.mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(files); - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); + this.mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); - this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo1)); - this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo2)).Throws(); + this.mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo1)); + this.mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo2)).Throws(); // Act - this._mockFolderManager.Object.DeleteFolder(folderInfo, new List()); + this.mockFolderManager.Object.DeleteFolder(folderInfo, new List()); } [Test] public void DeleteFolder_Calls_FolderProvider_DeleteFolder() { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)).Verifiable(); + this.mockFolder.Setup(mf => mf.DeleteFolder(this.folderInfo.Object)).Verifiable(); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + this.mockFolderManager.Object.DeleteFolder(this.folderInfo.Object); - this._mockFolder.Verify(); + this.mockFolder.Verify(); } [Test] [ExpectedException(typeof(FolderProviderException))] public void DeleteFolder_Throws_When_FolderProvider_Throws() { - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)).Throws(); + this.mockFolder.Setup(mf => mf.DeleteFolder(this.folderInfo.Object)).Throws(); - this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + this.mockFolderManager.Object.DeleteFolder(this.folderInfo.Object); } [Test] public void DeleteFolder_Calls_Directory_Delete_When_Directory_Exists() { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)); + this.mockFolder.Setup(mf => mf.DeleteFolder(this.folderInfo.Object)); - this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - this._directory.Setup(d => d.Delete(Constants.FOLDER_ValidFolderPath, true)).Verifiable(); + this.directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + this.directory.Setup(d => d.Delete(Constants.FOLDER_ValidFolderPath, true)).Verifiable(); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + this.mockFolderManager.Object.DeleteFolder(this.folderInfo.Object); - this._directory.Verify(); + this.directory.Verify(); } [Test] public void DeleteFolder_Calls_FolderManager_DeleteFolder_Overload() { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)); + this.mockFolder.Setup(mf => mf.DeleteFolder(this.folderInfo.Object)); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); - this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + this.mockFolderManager.Object.DeleteFolder(this.folderInfo.Object); - this._mockFolderManager.Verify(); + this.mockFolderManager.Verify(); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderPath() { - this._folderManager.FolderExists(Constants.CONTENT_ValidPortalId, null); + this.folderManager.FolderExists(Constants.CONTENT_ValidPortalId, null); } [Test] public void ExistsFolder_Calls_FolderManager_GetFolder() { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object).Verifiable(); + this.mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this.folderInfo.Object).Verifiable(); - this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + this.mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - this._mockFolderManager.Verify(); + this.mockFolderManager.Verify(); } [Test] public void ExistsFolder_Returns_True_When_Folder_Exists() { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); + this.mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this.folderInfo.Object); - var result = this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + var result = this.mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); Assert.IsTrue(result); } @@ -514,9 +526,9 @@ public void ExistsFolder_Returns_True_When_Folder_Exists() [Test] public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); + this.mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); - var result = this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + var result = this.mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); Assert.IsFalse(result); } @@ -525,36 +537,36 @@ public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() [ExpectedException(typeof(ArgumentNullException))] public void GetFilesByFolder_Throws_On_Null_Folder() { - this._folderManager.GetFiles(null); + this.folderManager.GetFiles(null); } [Test] public void GetFilesByFolder_Calls_DataProvider_GetFiles() { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); var files = new DataTable(); files.Columns.Add("FolderName"); var dr = files.CreateDataReader(); - this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr).Verifiable(); + this.mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr).Verifiable(); var filesList = new List { new FileInfo() { FileName = Constants.FOLDER_ValidFileName } }; - this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + this.cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - this._folderManager.GetFiles(this._folderInfo.Object); + this.folderManager.GetFiles(this.folderInfo.Object); - this._mockData.Verify(); + this.mockData.Verify(); } [Test] public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count() { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); var files = new DataTable(); files.Columns.Add("FileName"); @@ -562,13 +574,13 @@ public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count() var dr = files.CreateDataReader(); - this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); + this.mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); var filesList = new List { new FileInfo { FileName = Constants.FOLDER_ValidFileName } }; - this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + this.cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - var result = this._folderManager.GetFiles(this._folderInfo.Object).ToList(); + var result = this.folderManager.GetFiles(this.folderInfo.Object).ToList(); Assert.AreEqual(1, result.Count); } @@ -576,8 +588,8 @@ public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count() [Test] public void GetFilesByFolder_Returns_Valid_FileNames_When_Folder_Contains_Files() { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); var files = new DataTable(); files.Columns.Add("FileName"); @@ -586,7 +598,7 @@ public void GetFilesByFolder_Returns_Valid_FileNames_When_Folder_Contains_Files( var dr = files.CreateDataReader(); - this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); + this.mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); var filesList = new List { @@ -594,9 +606,9 @@ public void GetFilesByFolder_Returns_Valid_FileNames_When_Folder_Contains_Files( new FileInfo { FileName = Constants.FOLDER_OtherValidFileName }, }; - this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + this.cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - var result = this._folderManager.GetFiles(this._folderInfo.Object).Cast(); + var result = this.folderManager.GetFiles(this.folderInfo.Object).Cast(); CollectionAssert.AreEqual(filesList, result); } @@ -607,11 +619,11 @@ public void GetFolder_Calls_DataProvider_GetFolder() var folderDataTable = new DataTable(); folderDataTable.Columns.Add("FolderName"); - this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(folderDataTable.CreateDataReader()).Verifiable(); + this.mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(folderDataTable.CreateDataReader()).Verifiable(); - this._folderManager.GetFolder(Constants.FOLDER_ValidFolderId); + this.folderManager.GetFolder(Constants.FOLDER_ValidFolderId); - this._mockData.Verify(); + this.mockData.Verify(); } [Test] @@ -622,10 +634,10 @@ public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist() var dr = folderDataTable.CreateDataReader(); - this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); - this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); + this.mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); + this.cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); - var result = this._folderManager.GetFolder(Constants.FOLDER_ValidFolderId); + var result = this.folderManager.GetFolder(Constants.FOLDER_ValidFolderId); Assert.IsNull(result); } @@ -633,9 +645,9 @@ public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist() [Test] public void GetFolder_Returns_Valid_Folder_When_Folder_Exists() { - this._folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); + this.folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); - this._pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); + this.pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); var folderDataTable = new DataTable(); folderDataTable.Columns.Add("FolderName"); @@ -643,13 +655,13 @@ public void GetFolder_Returns_Valid_Folder_When_Folder_Exists() var dr = folderDataTable.CreateDataReader(); - this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); + this.mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath }; - this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); + this.cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); - var result = this._mockFolderManager.Object.GetFolder(Constants.FOLDER_ValidFolderId); + var result = this.mockFolderManager.Object.GetFolder(Constants.FOLDER_ValidFolderId); Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName); } @@ -658,7 +670,7 @@ public void GetFolder_Returns_Valid_Folder_When_Folder_Exists() [ExpectedException(typeof(ArgumentNullException))] public void GetFolder_Throws_On_Null_FolderPath() { - this._folderManager.GetFolder(It.IsAny(), null); + this.folderManager.GetFolder(It.IsAny(), null); } [Test] @@ -666,25 +678,25 @@ public void GetFolder_Calls_GetFolders() { var foldersSorted = new List(); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted).Verifiable(); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted).Verifiable(); - this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + this.mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - this._mockFolderManager.Verify(); + this.mockFolderManager.Verify(); } [Test] public void GetFolder_Calls_DataProvider_GetFolder_When_Folder_Is_Not_In_Cache() { - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); var foldersSorted = new List(); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); - this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + this.mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - this._mockData.Verify(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath), Times.Once()); + this.mockData.Verify(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath), Times.Once()); } [Test] @@ -695,13 +707,13 @@ public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist_Overload() var dr = folderDataTable.CreateDataReader(); - this._mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); + this.mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); - this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); + this.cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - var result = this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + var result = this.mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); Assert.IsNull(result); } @@ -709,8 +721,8 @@ public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist_Overload() [Test] public void GetFolder_Returns_Valid_Folder_When_Folder_Exists_Overload() { - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); + this.pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); var folderDataTable = new DataTable(); folderDataTable.Columns.Add("FolderName"); @@ -718,15 +730,15 @@ public void GetFolder_Returns_Valid_Folder_When_Folder_Exists_Overload() var dr = folderDataTable.CreateDataReader(); - this._mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); + this.mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath }; - this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); + this.cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - var result = this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + var result = this.mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName); } @@ -735,17 +747,17 @@ public void GetFolder_Returns_Valid_Folder_When_Folder_Exists_Overload() [ExpectedException(typeof(ArgumentNullException))] public void GetFoldersByParentFolder_Throws_On_Null_ParentFolder() { - this._folderManager.GetFolders((IFolderInfo)null); + this.folderManager.GetFolders((IFolderInfo)null); } [Test] public void GetFoldersByParentFolder_Returns_Empty_List_When_ParentFolder_Contains_No_Subfolders() { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - var result = this._mockFolderManager.Object.GetFolders(this._folderInfo.Object).ToList(); + var result = this.mockFolderManager.Object.GetFolders(this.folderInfo.Object).ToList(); Assert.AreEqual(0, result.Count); } @@ -753,8 +765,8 @@ public void GetFoldersByParentFolder_Returns_Empty_List_When_ParentFolder_Contai [Test] public void GetFoldersByParentFolder_Returns_Valid_Subfolders() { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); var foldersSorted = new List { @@ -762,9 +774,9 @@ public void GetFoldersByParentFolder_Returns_Valid_Subfolders() new FolderInfo { FolderID = Constants.FOLDER_OtherValidFolderId, ParentID = Constants.FOLDER_ValidFolderId }, }; - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); - var result = this._mockFolderManager.Object.GetFolders(this._folderInfo.Object).ToList(); + var result = this.mockFolderManager.Object.GetFolders(this.folderInfo.Object).ToList(); Assert.AreEqual(1, result.Count); Assert.AreEqual(Constants.FOLDER_OtherValidFolderId, result[0].FolderID); @@ -775,18 +787,18 @@ public void GetFolders_Calls_CBO_GetCachedObject() { var folders = new List(); - this._cbo.Setup(cbo => cbo.GetCachedObject>(It.IsAny(), It.IsAny(), false)).Returns(folders).Verifiable(); + this.cbo.Setup(cbo => cbo.GetCachedObject>(It.IsAny(), It.IsAny(), false)).Returns(folders).Verifiable(); - this._mockFolderManager.Object.GetFolders(Constants.CONTENT_ValidPortalId); + this.mockFolderManager.Object.GetFolders(Constants.CONTENT_ValidPortalId); - this._cbo.Verify(); + this.cbo.Verify(); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void RenameFolder_Throws_On_Null_Folder() { - this._folderManager.RenameFolder(null, It.IsAny()); + this.folderManager.RenameFolder(null, It.IsAny()); } [Test] @@ -795,41 +807,41 @@ public void RenameFolder_Throws_On_Null_Folder() [ExpectedException(typeof(ArgumentException))] public void RenameFolder_Throws_On_Null_Or_Empty_NewFolderName(string newFolderName) { - this._folderManager.RenameFolder(this._folderInfo.Object, newFolderName); + this.folderManager.RenameFolder(this.folderInfo.Object, newFolderName); } [Test] [ExpectedException(typeof(FolderAlreadyExistsException))] public void RenameFolder_Throws_When_DestinationFolder_Exists() { - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderName)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + this.pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderName)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); + this.mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); - this._mockFolderManager.Object.RenameFolder(this._folderInfo.Object, Constants.FOLDER_OtherValidFolderName); + this.mockFolderManager.Object.RenameFolder(this.folderInfo.Object, Constants.FOLDER_OtherValidFolderName); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFolder_Throws_On_Null_Folder() { - this._folderManager.UpdateFolder(null); + this.folderManager.UpdateFolder(null); } [Test] public void UpdateFolder_Calls_DataProvider_UpdateFolder() { - this._mockFolderManager.Setup(mfm => mfm.AddLogEntry(this._folderInfo.Object, It.IsAny())); - this._mockFolderManager.Setup(mfm => mfm.SaveFolderPermissions(this._folderInfo.Object)); - this._mockFolderManager.Setup(mfm => mfm.ClearFolderCache(It.IsAny())); + this.mockFolderManager.Setup(mfm => mfm.AddLogEntry(this.folderInfo.Object, It.IsAny())); + this.mockFolderManager.Setup(mfm => mfm.SaveFolderPermissions(this.folderInfo.Object)); + this.mockFolderManager.Setup(mfm => mfm.ClearFolderCache(It.IsAny())); - this._mockFolderManager.Object.UpdateFolder(this._folderInfo.Object); + this.mockFolderManager.Object.UpdateFolder(this.folderInfo.Object); - this._mockData.Verify( + this.mockData.Verify( md => md.UpdateFolder( It.IsAny(), It.IsAny(), @@ -851,27 +863,27 @@ public void UpdateFolder_Calls_DataProvider_UpdateFolder() [ExpectedException(typeof(ArgumentNullException))] public void SynchronizeFolder_Throws_On_Null_RelativePath() { - this._folderManager.Synchronize(It.IsAny(), null, It.IsAny(), It.IsAny()); + this.folderManager.Synchronize(It.IsAny(), null, It.IsAny(), It.IsAny()); } [Test] [ExpectedException(typeof(NoNetworkAvailableException))] public void SynchronizeFolder_Throws_When_Some_Folder_Mapping_Requires_Network_Connectivity_But_There_Is_No_Network_Available() { - this._mockFolderManager.Setup(mfm => mfm.AreThereFolderMappingsRequiringNetworkConnectivity(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false)).Returns(true); - this._mockFolderManager.Setup(mfm => mfm.IsNetworkAvailable()).Returns(false); + this.mockFolderManager.Setup(mfm => mfm.AreThereFolderMappingsRequiringNetworkConnectivity(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false)).Returns(true); + this.mockFolderManager.Setup(mfm => mfm.IsNetworkAvailable()).Returns(false); - this._mockFolderManager.Object.Synchronize(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false, false); + this.mockFolderManager.Object.Synchronize(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false, false); } [Test] public void GetFileSystemFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() { - this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this.pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); + this.directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); - var result = this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + var result = this.mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); Assert.IsEmpty(result); } @@ -879,11 +891,11 @@ public void GetFileSystemFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() [Test] public void GetFileSystemFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive() { - this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this.pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + this.directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - var result = this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + var result = this.mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); Assert.AreEqual(1, result.Count); Assert.IsTrue(result.Values[0].ExistsInFileSystem); @@ -892,28 +904,28 @@ public void GetFileSystemFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_ [Test] public void GetFileSystemFolders_Calls_FolderManager_GetFileSystemFoldersRecursive_When_Folder_Exists_And_Is_Recursive() { - this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) + this.pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) .Returns(Constants.FOLDER_ValidFolderPath); - this._mockFolderManager.Setup(mfm => mfm.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)) + this.mockFolderManager.Setup(mfm => mfm.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)) .Returns(It.IsAny>()) .Verifiable(); - this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + this.directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); + this.mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); - this._mockFolderManager.Verify(); + this.mockFolderManager.Verify(); } [Test] public void GetFileSystemFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() { - this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._directory.Setup(d => d.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]); + this.directory.Setup(d => d.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]); - var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath); + var result = this.mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath); Assert.AreEqual(1, result.Count); } @@ -930,15 +942,15 @@ public void GetFileSystemFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree { @"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/" }, }; - this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) + this.pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) .Returns((portalID, physicalPath) => relativePaths[physicalPath]); var directories = new List { @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; - this._directory.Setup(d => d.GetDirectories(It.IsAny())) + this.directory.Setup(d => d.GetDirectories(It.IsAny())) .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); - var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); + var result = this.mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); Assert.AreEqual(5, result.Count); } @@ -955,15 +967,15 @@ public void GetFileSystemFoldersRecursive_Sets_ExistsInFileSystem_For_All_Items( { @"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/" }, }; - this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) + this.pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) .Returns((portalID, physicalPath) => relativePaths[physicalPath]); var directories = new List { @"C:\folder", @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; - this._directory.Setup(d => d.GetDirectories(It.IsAny())) + this.directory.Setup(d => d.GetDirectories(It.IsAny())) .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); - var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); + var result = this.mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); foreach (var mergedTreeItem in result.Values) { @@ -974,9 +986,9 @@ public void GetFileSystemFoldersRecursive_Sets_ExistsInFileSystem_For_All_Items( [Test] public void GetDatabaseFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); + this.mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); - var result = this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + var result = this.mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); Assert.IsEmpty(result); } @@ -984,9 +996,9 @@ public void GetDatabaseFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() [Test] public void GetDatabaseFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive() { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); + this.mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this.folderInfo.Object); - var result = this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + var result = this.mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); Assert.AreEqual(1, result.Count); Assert.IsTrue(result.Values[0].ExistsInDatabase); @@ -995,29 +1007,29 @@ public void GetDatabaseFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Re [Test] public void GetDatabaseFolders_Calls_FolderManager_GetDatabaseFoldersRecursive_When_Folder_Exists_And_Is_Recursive() { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) - .Returns(this._folderInfo.Object); + this.mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) + .Returns(this.folderInfo.Object); - this._mockFolderManager.Setup(mfm => mfm.GetDatabaseFoldersRecursive(this._folderInfo.Object)) + this.mockFolderManager.Setup(mfm => mfm.GetDatabaseFoldersRecursive(this.folderInfo.Object)) .Returns(It.IsAny>()) .Verifiable(); - this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); + this.mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); - this._mockFolderManager.Verify(); + this.mockFolderManager.Verify(); } [Test] public void GetDatabaseFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() { - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var subfolders = new List(); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(this._folderInfo.Object)).Returns(subfolders); + this.mockFolderManager.Setup(mfm => mfm.GetFolders(this.folderInfo.Object)).Returns(subfolders); - var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); + var result = this.mockFolderManager.Object.GetDatabaseFoldersRecursive(this.folderInfo.Object); Assert.AreEqual(1, result.Count); } @@ -1025,8 +1037,8 @@ public void GetDatabaseFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Ha [Test] public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() { - this._folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var subfolders = new List { @@ -1036,13 +1048,13 @@ public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() new FolderInfo { FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, }; - this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) + this.mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) .Returns(parent => subfolders.FindAll(sub => sub.FolderPath.StartsWith(parent.FolderPath) && sub.FolderPath.Length > parent.FolderPath.Length && sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); - var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); + var result = this.mockFolderManager.Object.GetDatabaseFoldersRecursive(this.folderInfo.Object); Assert.AreEqual(5, result.Count); } @@ -1050,8 +1062,8 @@ public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() [Test] public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() { - this._folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var subfolders = new List { @@ -1061,13 +1073,13 @@ public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() new FolderInfo() { FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, }; - this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) + this.mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) .Returns(parent => subfolders.FindAll(sub => sub.FolderPath.StartsWith(parent.FolderPath) && sub.FolderPath.Length > parent.FolderPath.Length && sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); - var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); + var result = this.mockFolderManager.Object.GetDatabaseFoldersRecursive(this.folderInfo.Object); foreach (var mergedTreeItem in result.Values) { @@ -1150,7 +1162,7 @@ public void MergeFolderLists_Returns_Empty_List_When_Both_Lists_Are_Empty() var list1 = new SortedList(); var list2 = new SortedList(); - var result = this._folderManager.MergeFolderLists(list1, list2); + var result = this.folderManager.MergeFolderLists(list1, list2); Assert.IsEmpty(result); } @@ -1170,7 +1182,7 @@ public void MergeFolderLists_Count_Equals_The_Intersection_Count_Between_Both_Li { "folder3", new FolderManager.MergedTreeItem { FolderPath = "folder3" } }, }; - var result = this._folderManager.MergeFolderLists(list1, list2); + var result = this.folderManager.MergeFolderLists(list1, list2); Assert.AreEqual(3, result.Count); } @@ -2081,7 +2093,7 @@ public void MergeFolderLists_Count_Equals_The_Intersection_Count_Between_Both_Li [ExpectedException(typeof(ArgumentNullException))] public void MoveFolder_Throws_On_Null_Folder() { - this._folderManager.MoveFolder(null, It.IsAny()); + this.folderManager.MoveFolder(null, It.IsAny()); } [Test] @@ -2090,42 +2102,42 @@ public void MoveFolder_Throws_On_Null_Folder() [ExpectedException(typeof(ArgumentException))] public void MoveFolder_Throws_On_Null_Or_Emtpy_NewFolderPath(string newFolderPath) { - this._folderManager.MoveFolder(this._folderInfo.Object, newFolderPath); + this.folderManager.MoveFolder(this.folderInfo.Object, newFolderPath); } [Test] public void MoveFolder_Returns_The_Same_Folder_If_The_Paths_Are_The_Same() { - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); IFolderInfo destinationFolder = new FolderInfo(); destinationFolder.FolderPath = Constants.FOLDER_ValidFolderRelativePath; - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - var movedFolder = this._folderManager.MoveFolder(this._folderInfo.Object, destinationFolder); + var movedFolder = this.folderManager.MoveFolder(this.folderInfo.Object, destinationFolder); - Assert.AreEqual(this._folderInfo.Object, movedFolder); + Assert.AreEqual(this.folderInfo.Object, movedFolder); } [Test] [ExpectedException(typeof(InvalidOperationException))] public void MoveFolder_Throws_When_Move_Operation_Is_Not_Valid() { - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); IFolderInfo destinationFolder = new FolderInfo(); destinationFolder.FolderPath = Constants.FOLDER_OtherValidFolderRelativePath; destinationFolder.FolderMappingID = Constants.FOLDER_ValidFolderMappingID; - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + this.pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - this._mockFolderManager.Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())).Returns(false); - this._mockFolderManager.Setup(mfm => mfm.CanMoveBetweenFolderMappings(It.IsAny(), It.IsAny())).Returns(true); - this._mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(this._folderInfo.Object, destinationFolder, It.IsAny())).Returns(false); + this.mockFolderManager.Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())).Returns(false); + this.mockFolderManager.Setup(mfm => mfm.CanMoveBetweenFolderMappings(It.IsAny(), It.IsAny())).Returns(true); + this.mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(this.folderInfo.Object, destinationFolder, It.IsAny())).Returns(false); - this._mockFolderManager.Object.MoveFolder(this._folderInfo.Object, destinationFolder); + this.mockFolderManager.Object.MoveFolder(this.folderInfo.Object, destinationFolder); } // [Test] @@ -2184,9 +2196,9 @@ public void MoveFolder_Throws_When_Move_Operation_Is_Not_Valid() [Test] public void OverwriteFolder_Calls_MoveFile_For_Each_File_In_Source_Folder() { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var destinationFolder = new FolderInfo(); @@ -2195,21 +2207,21 @@ public void OverwriteFolder_Calls_MoveFile_For_Each_File_In_Source_Folder() var file3 = new FileInfo(); var files = new List { file1, file2, file3 }; - this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + this.mockFolderManager.Setup(mfm => mfm.GetFiles(this.folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); var fileManager = new Mock(); FileManager.RegisterInstance(fileManager.Object); fileManager.Setup(fm => fm.MoveFile(It.IsAny(), destinationFolder)); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); var folderMapping = new FolderMappingInfo(); - this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); + this.mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); - this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); + this.mockFolderManager.Object.OverwriteFolder(this.folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); fileManager.Verify(fm => fm.MoveFile(It.IsAny(), destinationFolder), Times.Exactly(3)); } @@ -2220,25 +2232,25 @@ public void OverwriteFolder_Deletes_Source_Folder_In_Database() var fileManager = new Mock(); FileManager.RegisterInstance(fileManager.Object); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var files = new List(); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + this.mockFolderManager.Setup(mfm => mfm.GetFiles(this.folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); var destinationFolder = new FolderInfo(); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); var folderMapping = new FolderMappingInfo(); - this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); + this.mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); - this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); + this.mockFolderManager.Object.OverwriteFolder(this.folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); - this._mockFolderManager.Verify(); + this.mockFolderManager.Verify(); } [Test] @@ -2247,24 +2259,24 @@ public void OverwriteFolder_Adds_Folder_To_FoldersToDelete_If_FolderMapping_Is_E var fileManager = new Mock(); FileManager.RegisterInstance(fileManager.Object); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this.folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this.folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this.folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var files = new List(); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + this.mockFolderManager.Setup(mfm => mfm.GetFiles(this.folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); var destinationFolder = new FolderInfo(); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this.mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); var folderMapping = new FolderMappingInfo(); - this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true); + this.mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this.mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true); var foldersToDelete = new SortedList(); - this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), foldersToDelete); + this.mockFolderManager.Object.OverwriteFolder(this.folderInfo.Object, destinationFolder, new Dictionary(), foldersToDelete); Assert.AreEqual(1, foldersToDelete.Count); } @@ -2314,5 +2326,5 @@ public void OverwriteFolder_Adds_Folder_To_FoldersToDelete_If_FolderMapping_Is_E // _mockFolderManager.Verify(); // } - } -} + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs index 27124f48d3c..b35121031bc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs @@ -2,168 +2,188 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Services.Mobile -{ - using System; - using System.Collections.Generic; - using System.Data; - - using DotNetNuke.ComponentModel; - using DotNetNuke.Data; - using DotNetNuke.Services.Mobile; - using DotNetNuke.Tests.Utilities.Mocks; - using Moq; - using NUnit.Framework; - - /// - /// Summary description for PreviewProfileControllerTests. - /// - [TestFixture] - public class PreviewProfileControllerTests - { - private Mock _dataProvider; - - private DataTable _dtProfiles; - - [SetUp] - public void SetUp() - { - ComponentFactory.Container = new SimpleContainer(); - this._dataProvider = MockComponentProvider.CreateDataProvider(); - this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - MockComponentProvider.CreateDataCacheProvider(); - MockComponentProvider.CreateEventLogController(); - - this._dtProfiles = new DataTable("PreviewProfiles"); - var pkCol = this._dtProfiles.Columns.Add("Id", typeof(int)); - this._dtProfiles.Columns.Add("PortalId", typeof(int)); - this._dtProfiles.Columns.Add("Name", typeof(string)); - this._dtProfiles.Columns.Add("Width", typeof(int)); - this._dtProfiles.Columns.Add("Height", typeof(int)); - this._dtProfiles.Columns.Add("UserAgent", typeof(string)); - this._dtProfiles.Columns.Add("SortOrder", typeof(int)); - - this._dtProfiles.PrimaryKey = new[] { pkCol }; - - this._dataProvider.Setup(d => - d.SavePreviewProfile( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())).Returns( - (id, portalId, name, width, height, userAgent, sortOrder, userId) => - { - if (id == -1) - { - if (this._dtProfiles.Rows.Count == 0) - { - id = 1; - } - else - { - id = Convert.ToInt32(this._dtProfiles.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; - } - - var row = this._dtProfiles.NewRow(); - row["Id"] = id; - row["PortalId"] = portalId; - row["name"] = name; - row["width"] = width; - row["height"] = height; - row["useragent"] = userAgent; - row["sortorder"] = sortOrder; - - this._dtProfiles.Rows.Add(row); - } - else - { - var rows = this._dtProfiles.Select("Id = " + id); - if (rows.Length == 1) - { - var row = rows[0]; - - row["name"] = name; - row["width"] = width; - row["height"] = height; - row["useragent"] = userAgent; - row["sortorder"] = sortOrder; - } - } - - return id; - }); - - this._dataProvider.Setup(d => d.GetPreviewProfiles(It.IsAny())).Returns((portalId) => { return this.GetProfilesCallBack(portalId); }); - this._dataProvider.Setup(d => d.DeletePreviewProfile(It.IsAny())).Callback((id) => - { - var rows = this._dtProfiles.Select("Id = " + id); - if (rows.Length == 1) - { - this._dtProfiles.Rows.Remove(rows[0]); - } - }); - } - - [Test] - public void PreviewProfileController_Save_Valid_Profile() - { - var profile = new PreviewProfile { Name = "Test R", PortalId = 0, Width = 800, Height = 480 }; - new PreviewProfileController().Save(profile); - - var dataReader = this._dataProvider.Object.GetPreviewProfiles(0); - var affectedCount = 0; - while (dataReader.Read()) - { - affectedCount++; - } - - Assert.AreEqual(1, affectedCount); - } - - [Test] - public void PreviewProfileController_GetProfilesByPortal_With_Valid_PortalID() - { - this.PrepareData(); - - IList list = new PreviewProfileController().GetProfilesByPortal(0); - - Assert.AreEqual(3, list.Count); - } - - [Test] - public void PreviewProfileController_Delete_With_ValidID() - { - this.PrepareData(); - new PreviewProfileController().Delete(0, 1); - - IList list = new PreviewProfileController().GetProfilesByPortal(0); - - Assert.AreEqual(2, list.Count); - } - - private IDataReader GetProfilesCallBack(int portalId) - { - var dtCheck = this._dtProfiles.Clone(); - foreach (var row in this._dtProfiles.Select("PortalId = " + portalId)) - { - dtCheck.Rows.Add(row.ItemArray); - } - - return dtCheck.CreateDataReader(); - } - - private void PrepareData() - { - this._dtProfiles.Rows.Add(1, 0, "R1", 640, 480, string.Empty, 1); - this._dtProfiles.Rows.Add(2, 0, "R2", 640, 480, string.Empty, 2); - this._dtProfiles.Rows.Add(3, 0, "R3", 640, 480, string.Empty, 3); - this._dtProfiles.Rows.Add(4, 1, "R4", 640, 480, string.Empty, 4); - this._dtProfiles.Rows.Add(5, 1, "R5", 640, 480, string.Empty, 5); - this._dtProfiles.Rows.Add(6, 1, "R6", 640, 480, string.Empty, 6); - } - } -} +namespace DotNetNuke.Tests.Core.Services.Mobile +{ + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Mobile; + using DotNetNuke.Tests.Utilities.Mocks; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + /// + /// Summary description for PreviewProfileControllerTests. + /// + [TestFixture] + public class PreviewProfileControllerTests + { + private Mock dataProvider; + + private DataTable dtProfiles; + + [SetUp] + public void SetUp() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + ComponentFactory.Container = new SimpleContainer(); + this.dataProvider = MockComponentProvider.CreateDataProvider(); + this.dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + MockComponentProvider.CreateDataCacheProvider(); + MockComponentProvider.CreateEventLogController(); + + this.dtProfiles = new DataTable("PreviewProfiles"); + var pkCol = this.dtProfiles.Columns.Add("Id", typeof(int)); + this.dtProfiles.Columns.Add("PortalId", typeof(int)); + this.dtProfiles.Columns.Add("Name", typeof(string)); + this.dtProfiles.Columns.Add("Width", typeof(int)); + this.dtProfiles.Columns.Add("Height", typeof(int)); + this.dtProfiles.Columns.Add("UserAgent", typeof(string)); + this.dtProfiles.Columns.Add("SortOrder", typeof(int)); + + this.dtProfiles.PrimaryKey = new[] { pkCol }; + + this.dataProvider.Setup(d => + d.SavePreviewProfile( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())).Returns( + (id, portalId, name, width, height, userAgent, sortOrder, userId) => + { + if (id == -1) + { + if (this.dtProfiles.Rows.Count == 0) + { + id = 1; + } + else + { + id = Convert.ToInt32(this.dtProfiles.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; + } + + var row = this.dtProfiles.NewRow(); + row["Id"] = id; + row["PortalId"] = portalId; + row["name"] = name; + row["width"] = width; + row["height"] = height; + row["useragent"] = userAgent; + row["sortorder"] = sortOrder; + + this.dtProfiles.Rows.Add(row); + } + else + { + var rows = this.dtProfiles.Select("Id = " + id); + if (rows.Length == 1) + { + var row = rows[0]; + + row["name"] = name; + row["width"] = width; + row["height"] = height; + row["useragent"] = userAgent; + row["sortorder"] = sortOrder; + } + } + + return id; + }); + + this.dataProvider.Setup(d => d.GetPreviewProfiles(It.IsAny())).Returns((portalId) => { return this.GetProfilesCallBack(portalId); }); + this.dataProvider.Setup(d => d.DeletePreviewProfile(It.IsAny())).Callback((id) => + { + var rows = this.dtProfiles.Select("Id = " + id); + if (rows.Length == 1) + { + this.dtProfiles.Rows.Remove(rows[0]); + } + }); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + } + + [Test] + public void PreviewProfileController_Save_Valid_Profile() + { + var profile = new PreviewProfile { Name = "Test R", PortalId = 0, Width = 800, Height = 480 }; + new PreviewProfileController().Save(profile); + + var dataReader = this.dataProvider.Object.GetPreviewProfiles(0); + var affectedCount = 0; + while (dataReader.Read()) + { + affectedCount++; + } + + Assert.AreEqual(1, affectedCount); + } + + [Test] + public void PreviewProfileController_GetProfilesByPortal_With_Valid_PortalID() + { + this.PrepareData(); + + IList list = new PreviewProfileController().GetProfilesByPortal(0); + + Assert.AreEqual(3, list.Count); + } + + [Test] + public void PreviewProfileController_Delete_With_ValidID() + { + this.PrepareData(); + new PreviewProfileController().Delete(0, 1); + + IList list = new PreviewProfileController().GetProfilesByPortal(0); + + Assert.AreEqual(2, list.Count); + } + + private IDataReader GetProfilesCallBack(int portalId) + { + var dtCheck = this.dtProfiles.Clone(); + foreach (var row in this.dtProfiles.Select("PortalId = " + portalId)) + { + dtCheck.Rows.Add(row.ItemArray); + } + + return dtCheck.CreateDataReader(); + } + + private void PrepareData() + { + this.dtProfiles.Rows.Add(1, 0, "R1", 640, 480, string.Empty, 1); + this.dtProfiles.Rows.Add(2, 0, "R2", 640, 480, string.Empty, 2); + this.dtProfiles.Rows.Add(3, 0, "R3", 640, 480, string.Empty, 3); + this.dtProfiles.Rows.Add(4, 1, "R4", 640, 480, string.Empty, 4); + this.dtProfiles.Rows.Add(5, 1, "R5", 640, 480, string.Empty, 5); + this.dtProfiles.Rows.Add(6, 1, "R6", 640, 480, string.Empty, 6); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs index e4cd277731a..afa656beecc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs @@ -2,960 +2,962 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Services.Mobile -{ - using System; - using System.Collections.Generic; - using System.Collections.Specialized; - using System.Data; - using System.Reflection; - using System.Web; +namespace DotNetNuke.Tests.Core.Services.Mobile +{ + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Data; + using System.Reflection; + using System.Web; using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; - using DotNetNuke.Common; - using DotNetNuke.Common.Internal; - using DotNetNuke.ComponentModel; - using DotNetNuke.Data; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Tabs; - using DotNetNuke.Security.Roles; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.ClientCapability; - using DotNetNuke.Services.Mobile; - using DotNetNuke.Tests.Core.Services.ClientCapability; - using DotNetNuke.Tests.Instance.Utilities; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.ClientCapability; + using DotNetNuke.Services.Mobile; + using DotNetNuke.Tests.Core.Services.ClientCapability; + using DotNetNuke.Tests.Instance.Utilities; using DotNetNuke.Tests.Utilities.Mocks; + using Microsoft.Extensions.DependencyInjection; - using Moq; - using NUnit.Framework; - - /// - /// Summary description for RedirectionControllerTests. - /// - [TestFixture] - public class RedirectionControllerTests - { - public const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; - public const string wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; - public const string msIE8UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; Creative AutoUpdate v1.40.02)"; - public const string msIE9UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; - public const string msIE10UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; - public const string fireFox5NT61UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:5.0) Gecko/20110619 Firefox/5.0"; - public const string iPadTabletUserAgent = "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10"; - public const string samsungGalaxyTablet = "Mozilla/5.0 (Linux; U; Android 2.2; en-gb; SAMSUNG GT-P1000 Tablet Build/MASTER) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; - public const string winTabletPC = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; Tablet PC 2.0)"; - public const string htcDesireVer1Sub22UserAgent = "Mozilla/5.0 (Linux; U; Android 2.2; sv-se; Desire_A8181 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; - public const string blackBerry9105V1 = "BlackBerry9105/5.0.0.696 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133"; - public const string motorolaRIZRSymbianOSOpera865 = "MOTORIZR-Z8/46.00.00 Mozilla/4.0 (compatible; MSIE 6.0; Symbian OS; 356) Opera 8.65 [it] UP.Link/6.3.0.0.0"; - - public const int Portal0 = 0; - public const int Portal1 = 1; - public const int Portal2 = 2; - public const int Page1 = 1; - public const int Page2 = 2; - public const int Page3 = 3; - public const int SortOrder1 = 1; - public const int SortOrder2 = 1; - public const int SortOrder3 = 1; - public const string PortalAlias0 = "www.portal0.com"; - public const string PortalAlias1 = "www.portal1.com"; - public const int AnotherPageOnSamePortal = 56; - public const int DeletedPageOnSamePortal = 59; - public const int DeletedPageOnSamePortal2 = 94; - public const int HomePageOnPortal0 = 55; - public const int HomePageOnPortal1 = 57; - public const int MobileLandingPage = 91; - public const int TabletLandingPage = 92; - public const int AllMobileLandingPage = 93; - public const bool EnabledFlag = true; - public const bool DisabledFlag = false; - public const bool IncludeChildTabsFlag = true; - public const string ExternalSite = "https://dnncommunity.org"; - - private const string DisableMobileRedirectCookieName = "disablemobileredirect"; - private const string DisableRedirectPresistCookieName = "disableredirectpresist"; - private const string DisableMobileRedirectQueryStringName = "nomo"; - - private Mock _dataProvider; - private RedirectionController _redirectionController; - private Mock _clientCapabilityProvider; - private Mock _mockHostController; - - private DataTable _dtRedirections; - private DataTable _dtRules; - - [SetUp] - public void SetUp() - { - this.SetupContianer(); - ComponentFactory.Container = new SimpleContainer(); - UnitTestHelper.ClearHttpContext(); - this._dataProvider = MockComponentProvider.CreateDataProvider(); - MockComponentProvider.CreateDataCacheProvider(); - MockComponentProvider.CreateEventLogController(); - this._clientCapabilityProvider = MockComponentProvider.CreateNew(); - this._mockHostController = new Mock(); - HostController.RegisterInstance(this._mockHostController.Object); - - this._redirectionController = new RedirectionController(); - - this.SetupDataProvider(); - this.SetupClientCapabilityProvider(); - this.SetupRoleProvider(); - - var tabController = TabController.Instance; - var dataProviderField = tabController.GetType().GetField("_dataProvider", BindingFlags.NonPublic | BindingFlags.Instance); - if (dataProviderField != null) - { - dataProviderField.SetValue(tabController, this._dataProvider.Object); - } - - - } - - [TearDown] - public void TearDown() - { - Globals.DependencyProvider = null; - TestableGlobals.ClearInstance(); - PortalController.ClearInstance(); - CachingProvider.Instance().PurgeCache(); - MockComponentProvider.ResetContainer(); - UnitTestHelper.ClearHttpContext(); - if (this._dtRedirections != null) - { - this._dtRedirections.Dispose(); - this._dtRedirections = null; - } - - if (this._dtRules != null) - { - this._dtRules.Dispose(); - this._dtRules = null; - } - - ComponentFactory.Container = null; - } - - [Test] - public void RedirectionController_Save_Valid_Redirection() - { - var redirection = new Redirection { Name = "Test R", PortalId = Portal0, SortOrder = 1, SourceTabId = -1, Type = RedirectionType.MobilePhone, TargetType = TargetType.Portal, TargetValue = Portal1 }; - this._redirectionController.Save(redirection); - - var dataReader = this._dataProvider.Object.GetRedirections(Portal0); - var affectedCount = 0; - while (dataReader.Read()) - { - affectedCount++; - } - - Assert.AreEqual(1, affectedCount); - } - - [Test] - public void RedirectionController_Save_ValidRedirection_With_Rules() - { - var redirection = new Redirection { Name = "Test R", PortalId = Portal0, SortOrder = 1, SourceTabId = -1, IncludeChildTabs = true, Type = RedirectionType.Other, TargetType = TargetType.Portal, TargetValue = Portal1 }; - redirection.MatchRules.Add(new MatchRule { Capability = "Platform", Expression = "IOS" }); - redirection.MatchRules.Add(new MatchRule { Capability = "Version", Expression = "5" }); - this._redirectionController.Save(redirection); - - var dataReader = this._dataProvider.Object.GetRedirections(Portal0); - var affectedCount = 0; - while (dataReader.Read()) - { - affectedCount++; - } - - Assert.AreEqual(1, affectedCount); - - var getRe = this._redirectionController.GetRedirectionsByPortal(Portal0)[0]; - Assert.AreEqual(2, getRe.MatchRules.Count); - } - - [Test] - public void RedirectionController_GetRedirectionsByPortal_With_Valid_PortalID() - { - this.PrepareData(); - - IList list = this._redirectionController.GetRedirectionsByPortal(Portal0); - - Assert.AreEqual(7, list.Count); - } - - [Test] - public void RedirectionController_Delete_With_ValidID() - { - this.PrepareData(); - this._redirectionController.Delete(Portal0, 1); - - IList list = this._redirectionController.GetRedirectionsByPortal(Portal0); - - Assert.AreEqual(6, list.Count); - } - - [Test] - public void RedirectionController_PurgeInvalidRedirections_DoNotPurgeRuleForNonDeletetedSource() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); - this._redirectionController.PurgeInvalidRedirections(0); - Assert.AreEqual(1, this._redirectionController.GetRedirectionsByPortal(0).Count); - } - - [Test] - public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedSource() - { - this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, DeletedPageOnSamePortal2, IncludeChildTabsFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag }); - this._redirectionController.PurgeInvalidRedirections(0); - Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); - } - - [Test] - public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedTargetPortal() - { - this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Portal, Portal2, EnabledFlag }); - this._redirectionController.PurgeInvalidRedirections(0); - Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); - } - - [Test] - public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedTargetTab() - { - this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, DeletedPageOnSamePortal2, EnabledFlag }); - this._redirectionController.PurgeInvalidRedirections(0); - Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void RedirectionController_GetRedirectionUrl_Throws_On_Null_UserAgent() - { - this._redirectionController.GetRedirectUrl(null, Portal0, 0); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Redirection_IsNotSet() - { - Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, HomePageOnPortal0)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Redirection_IsNotEnabled() - { - this.PrepareSingleDisabledRedirectionRule(); - Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, HomePageOnPortal0)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_UserAgent_Is_Desktop() - { - this.PrepareData(); - Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(msIE9UserAgent, Portal0, HomePageOnPortal0)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_CurrentPage_IsSameAs_TargetPage_OnMobile() - { - this.PreparePortalToAnotherPageOnSamePortal(); - Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_TargetPage_IsDeleted() - { - // prepare rule to a deleted tab on the same portal - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, AnotherPageOnSamePortal, EnabledFlag, (int)TargetType.Tab, DeletedPageOnSamePortal, 1); - Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_CurrentPortal_IsSameAs_TargetPortal_OnMobile() - { - this.PrepareSamePortalToSamePortalRedirectionRule(); - Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_TargetPageOnSamePortal_When_Surfing_HomePage_OnMobile() - { - this.PreparePortalToAnotherPageOnSamePortal(); - Assert.AreEqual(this.NavigateUrl(AnotherPageOnSamePortal), this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - } - - // [Test] - // public void RedirectionController_GetRedirectionUrl_Returns_HomePageOfOtherPortal_When_Surfing_AnyPageOfCurrentPortal_OnMobile() - // { - // PrepareHomePageToHomePageRedirectionRule(); - // Assert.AreEqual(DotNetNuke.Common.Globals.AddHTTP(PortalAlias1), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - // Assert.AreEqual(DotNetNuke.Common.Globals.AddHTTP(PortalAlias1), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 2)); - // } - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_ExternalSite_When_Surfing_AnyPageOfCurrentPortal_OnMobile() - { - this.PrepareExternalSiteRedirectionRule(); - Assert.AreEqual(ExternalSite, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - Assert.AreEqual(ExternalSite, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 2)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_MobileLanding_ForMobile_And_TabletLanding_ForTablet() - { - this.PrepareMobileAndTabletRedirectionRuleWithMobileFirst(); - Assert.AreEqual(this.NavigateUrl(MobileLandingPage), this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - Assert.AreEqual(this.NavigateUrl(TabletLandingPage), this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, Portal0, 1)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_TabletLanding_ForTablet_And_MobileLanding_ForMobile() - { - this.PrepareMobileAndTabletRedirectionRuleWithAndTabletRedirectionRuleTabletFirst(); - Assert.AreEqual(this.NavigateUrl(MobileLandingPage), this._redirectionController.GetRedirectUrl(iphoneUserAgent, 0, 1)); - Assert.AreEqual(this.NavigateUrl(TabletLandingPage), this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, 0, 1)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_SameLandingPage_For_AllMobile() - { - this.PrepareAllMobileRedirectionRule(); - string mobileLandingPage = this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1); - string tabletLandingPage = this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, Portal0, 1); - Assert.AreEqual(this.NavigateUrl(AllMobileLandingPage), mobileLandingPage); - Assert.AreEqual(this.NavigateUrl(AllMobileLandingPage), tabletLandingPage); - Assert.AreEqual(mobileLandingPage, tabletLandingPage); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Capability_DoesNot_Match() - { - this.PrepareOperaBrowserOnSymbianOSRedirectionRule(); - Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_ValidUrl_When_Capability_Matches() - { - this.PrepareOperaBrowserOnSymbianOSRedirectionRule(); - Assert.AreEqual(this.NavigateUrl(AnotherPageOnSamePortal), this._redirectionController.GetRedirectUrl(motorolaRIZRSymbianOSOpera865, Portal0, 1)); - } - - [Test] - public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_NotAll_Capability_Matches() - { - this.PrepareOperaBrowserOnIPhoneOSRedirectionRule(); - Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - } - - [Test] - public void RedirectionController_GetFullSiteUrl_With_NoRedirections() - { - var url = this._redirectionController.GetFullSiteUrl(Portal0, HomePageOnPortal0); - - Assert.AreEqual(string.Empty, url); - } - - // [Test] - // public void RedirectionController_GetFullSiteUrl_When_Redirect_Between_Different_Portals() - // { - // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, "1", 1); - - // var url = _redirectionController.GetFullSiteUrl(Portal1, HomePageOnPortal1); - - // Assert.AreEqual(Globals.AddHTTP(PortalAlias0), url); - // } - - // [Test] - // public void RedirectionController_GetFullSiteUrl_When_Redirect_In_Same_Portal() - // { - // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, 1); - - // var url = _redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); - - // //Assert.AreEqual(string.Empty, url); - // } - [Test] - public void RedirectionController_GetFullSiteUrl_When_Redirect_To_DifferentUrl() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Url, ExternalSite, 1); - - var url = this._redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); - - Assert.AreEqual(string.Empty, url); - } - - [Test] - public void RedirectionController_GetMobileSiteUrl_With_NoRedirections() - { - var url = this._redirectionController.GetMobileSiteUrl(Portal0, HomePageOnPortal0); - - Assert.AreEqual(string.Empty, url); - } - - [Test] - public void RedirectionController_GetMobileSiteUrl_Returns_Page_Specific_Url_When_Multiple_PageLevel_Redirects_Defined() - { - string redirectUrlPage1 = "m.yahoo.com"; - string redirectUrlPage2 = "m.cnn.com"; - - // first page goes to one url - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, Page1, EnabledFlag, (int)TargetType.Url, redirectUrlPage1, 1); - - // second page goes to another url (this is Tablet - it should not matter) - this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, Page2, EnabledFlag, (int)TargetType.Url, redirectUrlPage2, 1); - - var mobileUrlForPage1 = this._redirectionController.GetMobileSiteUrl(Portal0, Page1); - var mobileUrlForPage2 = this._redirectionController.GetMobileSiteUrl(Portal0, Page2); - var mobileUrlForPage3 = this._redirectionController.GetMobileSiteUrl(Portal0, Page3); - - // First Page returns link to first url - Assert.AreEqual(string.Format("{0}?nomo=0", redirectUrlPage1), mobileUrlForPage1); - - // Second Page returns link to second url - Assert.AreEqual(string.Format("{0}?nomo=0", redirectUrlPage2), mobileUrlForPage2); - - // Third Page returns link to first url - as this is the first found url and third page has no redirect defined - Assert.AreEqual(mobileUrlForPage3, string.Format("{0}?nomo=0", redirectUrlPage1)); - } - - // [Test] - // public void RedirectionController_GetMobileSiteUrl_Works_When_Page_Redirects_To_Another_Portal() - // { - // //first page goes to one second portal - // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, Portal1, 1); - - // var mobileUrlForPage1 = _redirectionController.GetMobileSiteUrl(Portal0, Page1); - - // //First Page returns link to home page of other portal - // Assert.AreEqual(Globals.AddHTTP(PortalAlias1), mobileUrlForPage1); - // } - [Test] - public void RedirectionController_GetMobileSiteUrl_When_Redirect_To_DifferentUrl() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Url, ExternalSite, 1); - - var url = this._redirectionController.GetMobileSiteUrl(Portal1, AnotherPageOnSamePortal); - - Assert.AreEqual(string.Empty, url); - } - - [Test] - public void RedirectionController_IsRedirectAllowedForTheSession_In_Normal_Action() - { - var app = this.GenerateApplication(); - - Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); - } - - [Test] - public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_1() - { - var app = this.GenerateApplication(); - app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "1"); - - Assert.IsFalse(this._redirectionController.IsRedirectAllowedForTheSession(app)); - Assert.IsNotNull(app.Request.Cookies[DisableMobileRedirectCookieName]); - Assert.IsNotNull(app.Request.Cookies[DisableRedirectPresistCookieName]); - } - - [Test] - public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_0() - { - var app = this.GenerateApplication(); - app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); - - Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); - } - - [Test] - public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_1_And_Then_Setback_To_0() - { - var app = this.GenerateApplication(); - app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "1"); - Assert.IsFalse(this._redirectionController.IsRedirectAllowedForTheSession(app)); - - app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); - Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); - } - - private void SetupContianer() - { - var serviceCollection = new ServiceCollection(); - - var mockNavigationManager = new Mock(); - mockNavigationManager.Setup(x => x.NavigateURL(It.IsAny())).Returns(x => this.NavigateUrl(x)); - + + using Moq; + + using NUnit.Framework; + + /// + /// Summary description for RedirectionControllerTests. + /// + [TestFixture] + public class RedirectionControllerTests + { + public const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; + public const string wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; + public const string msIE8UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; Creative AutoUpdate v1.40.02)"; + public const string msIE9UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; + public const string msIE10UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; + public const string fireFox5NT61UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:5.0) Gecko/20110619 Firefox/5.0"; + public const string iPadTabletUserAgent = "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10"; + public const string samsungGalaxyTablet = "Mozilla/5.0 (Linux; U; Android 2.2; en-gb; SAMSUNG GT-P1000 Tablet Build/MASTER) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; + public const string winTabletPC = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; Tablet PC 2.0)"; + public const string htcDesireVer1Sub22UserAgent = "Mozilla/5.0 (Linux; U; Android 2.2; sv-se; Desire_A8181 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; + public const string blackBerry9105V1 = "BlackBerry9105/5.0.0.696 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133"; + public const string motorolaRIZRSymbianOSOpera865 = "MOTORIZR-Z8/46.00.00 Mozilla/4.0 (compatible; MSIE 6.0; Symbian OS; 356) Opera 8.65 [it] UP.Link/6.3.0.0.0"; + + public const int Portal0 = 0; + public const int Portal1 = 1; + public const int Portal2 = 2; + public const int Page1 = 1; + public const int Page2 = 2; + public const int Page3 = 3; + public const int SortOrder1 = 1; + public const int SortOrder2 = 1; + public const int SortOrder3 = 1; + public const string PortalAlias0 = "www.portal0.com"; + public const string PortalAlias1 = "www.portal1.com"; + public const int AnotherPageOnSamePortal = 56; + public const int DeletedPageOnSamePortal = 59; + public const int DeletedPageOnSamePortal2 = 94; + public const int HomePageOnPortal0 = 55; + public const int HomePageOnPortal1 = 57; + public const int MobileLandingPage = 91; + public const int TabletLandingPage = 92; + public const int AllMobileLandingPage = 93; + public const bool EnabledFlag = true; + public const bool DisabledFlag = false; + public const bool IncludeChildTabsFlag = true; + public const string ExternalSite = "https://dnncommunity.org"; + + private const string DisableMobileRedirectCookieName = "disablemobileredirect"; + private const string DisableRedirectPresistCookieName = "disableredirectpresist"; + private const string DisableMobileRedirectQueryStringName = "nomo"; + + private Mock _dataProvider; + private RedirectionController _redirectionController; + private Mock _clientCapabilityProvider; + private Mock _mockHostController; + + private DataTable _dtRedirections; + private DataTable _dtRules; + + [SetUp] + public void SetUp() + { + this.SetupContianer(); + ComponentFactory.Container = new SimpleContainer(); + UnitTestHelper.ClearHttpContext(); + this._dataProvider = MockComponentProvider.CreateDataProvider(); + MockComponentProvider.CreateDataCacheProvider(); + MockComponentProvider.CreateEventLogController(); + this._clientCapabilityProvider = MockComponentProvider.CreateNew(); + this._mockHostController = new Mock(); + HostController.RegisterInstance(this._mockHostController.Object); + + this._redirectionController = new RedirectionController(); + + this.SetupDataProvider(); + this.SetupClientCapabilityProvider(); + this.SetupRoleProvider(); + + var tabController = TabController.Instance; + var dataProviderField = tabController.GetType().GetField("_dataProvider", BindingFlags.NonPublic | BindingFlags.Instance); + if (dataProviderField != null) + { + dataProviderField.SetValue(tabController, this._dataProvider.Object); + } + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + TestableGlobals.ClearInstance(); + PortalController.ClearInstance(); + CachingProvider.Instance().PurgeCache(); + MockComponentProvider.ResetContainer(); + UnitTestHelper.ClearHttpContext(); + if (this._dtRedirections != null) + { + this._dtRedirections.Dispose(); + this._dtRedirections = null; + } + + if (this._dtRules != null) + { + this._dtRules.Dispose(); + this._dtRules = null; + } + + ComponentFactory.Container = null; + } + + [Test] + public void RedirectionController_Save_Valid_Redirection() + { + var redirection = new Redirection { Name = "Test R", PortalId = Portal0, SortOrder = 1, SourceTabId = -1, Type = RedirectionType.MobilePhone, TargetType = TargetType.Portal, TargetValue = Portal1 }; + this._redirectionController.Save(redirection); + + var dataReader = this._dataProvider.Object.GetRedirections(Portal0); + var affectedCount = 0; + while (dataReader.Read()) + { + affectedCount++; + } + + Assert.AreEqual(1, affectedCount); + } + + [Test] + public void RedirectionController_Save_ValidRedirection_With_Rules() + { + var redirection = new Redirection { Name = "Test R", PortalId = Portal0, SortOrder = 1, SourceTabId = -1, IncludeChildTabs = true, Type = RedirectionType.Other, TargetType = TargetType.Portal, TargetValue = Portal1 }; + redirection.MatchRules.Add(new MatchRule { Capability = "Platform", Expression = "IOS" }); + redirection.MatchRules.Add(new MatchRule { Capability = "Version", Expression = "5" }); + this._redirectionController.Save(redirection); + + var dataReader = this._dataProvider.Object.GetRedirections(Portal0); + var affectedCount = 0; + while (dataReader.Read()) + { + affectedCount++; + } + + Assert.AreEqual(1, affectedCount); + + var getRe = this._redirectionController.GetRedirectionsByPortal(Portal0)[0]; + Assert.AreEqual(2, getRe.MatchRules.Count); + } + + [Test] + public void RedirectionController_GetRedirectionsByPortal_With_Valid_PortalID() + { + this.PrepareData(); + + IList list = this._redirectionController.GetRedirectionsByPortal(Portal0); + + Assert.AreEqual(7, list.Count); + } + + [Test] + public void RedirectionController_Delete_With_ValidID() + { + this.PrepareData(); + this._redirectionController.Delete(Portal0, 1); + + IList list = this._redirectionController.GetRedirectionsByPortal(Portal0); + + Assert.AreEqual(6, list.Count); + } + + [Test] + public void RedirectionController_PurgeInvalidRedirections_DoNotPurgeRuleForNonDeletetedSource() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); + this._redirectionController.PurgeInvalidRedirections(0); + Assert.AreEqual(1, this._redirectionController.GetRedirectionsByPortal(0).Count); + } + + [Test] + public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedSource() + { + this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, DeletedPageOnSamePortal2, IncludeChildTabsFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag }); + this._redirectionController.PurgeInvalidRedirections(0); + Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); + } + + [Test] + public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedTargetPortal() + { + this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Portal, Portal2, EnabledFlag }); + this._redirectionController.PurgeInvalidRedirections(0); + Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); + } + + [Test] + public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedTargetTab() + { + this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, DeletedPageOnSamePortal2, EnabledFlag }); + this._redirectionController.PurgeInvalidRedirections(0); + Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void RedirectionController_GetRedirectionUrl_Throws_On_Null_UserAgent() + { + this._redirectionController.GetRedirectUrl(null, Portal0, 0); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Redirection_IsNotSet() + { + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, HomePageOnPortal0)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Redirection_IsNotEnabled() + { + this.PrepareSingleDisabledRedirectionRule(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, HomePageOnPortal0)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_UserAgent_Is_Desktop() + { + this.PrepareData(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(msIE9UserAgent, Portal0, HomePageOnPortal0)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_CurrentPage_IsSameAs_TargetPage_OnMobile() + { + this.PreparePortalToAnotherPageOnSamePortal(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_TargetPage_IsDeleted() + { + // prepare rule to a deleted tab on the same portal + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, AnotherPageOnSamePortal, EnabledFlag, (int)TargetType.Tab, DeletedPageOnSamePortal, 1); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_CurrentPortal_IsSameAs_TargetPortal_OnMobile() + { + this.PrepareSamePortalToSamePortalRedirectionRule(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_TargetPageOnSamePortal_When_Surfing_HomePage_OnMobile() + { + this.PreparePortalToAnotherPageOnSamePortal(); + Assert.AreEqual(this.NavigateUrl(AnotherPageOnSamePortal), this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + } + + // [Test] + // public void RedirectionController_GetRedirectionUrl_Returns_HomePageOfOtherPortal_When_Surfing_AnyPageOfCurrentPortal_OnMobile() + // { + // PrepareHomePageToHomePageRedirectionRule(); + // Assert.AreEqual(DotNetNuke.Common.Globals.AddHTTP(PortalAlias1), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + // Assert.AreEqual(DotNetNuke.Common.Globals.AddHTTP(PortalAlias1), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 2)); + // } + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_ExternalSite_When_Surfing_AnyPageOfCurrentPortal_OnMobile() + { + this.PrepareExternalSiteRedirectionRule(); + Assert.AreEqual(ExternalSite, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + Assert.AreEqual(ExternalSite, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 2)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_MobileLanding_ForMobile_And_TabletLanding_ForTablet() + { + this.PrepareMobileAndTabletRedirectionRuleWithMobileFirst(); + Assert.AreEqual(this.NavigateUrl(MobileLandingPage), this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + Assert.AreEqual(this.NavigateUrl(TabletLandingPage), this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, Portal0, 1)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_TabletLanding_ForTablet_And_MobileLanding_ForMobile() + { + this.PrepareMobileAndTabletRedirectionRuleWithAndTabletRedirectionRuleTabletFirst(); + Assert.AreEqual(this.NavigateUrl(MobileLandingPage), this._redirectionController.GetRedirectUrl(iphoneUserAgent, 0, 1)); + Assert.AreEqual(this.NavigateUrl(TabletLandingPage), this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, 0, 1)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_SameLandingPage_For_AllMobile() + { + this.PrepareAllMobileRedirectionRule(); + string mobileLandingPage = this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1); + string tabletLandingPage = this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, Portal0, 1); + Assert.AreEqual(this.NavigateUrl(AllMobileLandingPage), mobileLandingPage); + Assert.AreEqual(this.NavigateUrl(AllMobileLandingPage), tabletLandingPage); + Assert.AreEqual(mobileLandingPage, tabletLandingPage); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Capability_DoesNot_Match() + { + this.PrepareOperaBrowserOnSymbianOSRedirectionRule(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_ValidUrl_When_Capability_Matches() + { + this.PrepareOperaBrowserOnSymbianOSRedirectionRule(); + Assert.AreEqual(this.NavigateUrl(AnotherPageOnSamePortal), this._redirectionController.GetRedirectUrl(motorolaRIZRSymbianOSOpera865, Portal0, 1)); + } + + [Test] + public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_NotAll_Capability_Matches() + { + this.PrepareOperaBrowserOnIPhoneOSRedirectionRule(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + } + + [Test] + public void RedirectionController_GetFullSiteUrl_With_NoRedirections() + { + var url = this._redirectionController.GetFullSiteUrl(Portal0, HomePageOnPortal0); + + Assert.AreEqual(string.Empty, url); + } + + // [Test] + // public void RedirectionController_GetFullSiteUrl_When_Redirect_Between_Different_Portals() + // { + // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, "1", 1); + + // var url = _redirectionController.GetFullSiteUrl(Portal1, HomePageOnPortal1); + + // Assert.AreEqual(Globals.AddHTTP(PortalAlias0), url); + // } + + // [Test] + // public void RedirectionController_GetFullSiteUrl_When_Redirect_In_Same_Portal() + // { + // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, 1); + + // var url = _redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); + + // //Assert.AreEqual(string.Empty, url); + // } + [Test] + public void RedirectionController_GetFullSiteUrl_When_Redirect_To_DifferentUrl() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Url, ExternalSite, 1); + + var url = this._redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); + + Assert.AreEqual(string.Empty, url); + } + + [Test] + public void RedirectionController_GetMobileSiteUrl_With_NoRedirections() + { + var url = this._redirectionController.GetMobileSiteUrl(Portal0, HomePageOnPortal0); + + Assert.AreEqual(string.Empty, url); + } + + [Test] + public void RedirectionController_GetMobileSiteUrl_Returns_Page_Specific_Url_When_Multiple_PageLevel_Redirects_Defined() + { + string redirectUrlPage1 = "m.yahoo.com"; + string redirectUrlPage2 = "m.cnn.com"; + + // first page goes to one url + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, Page1, EnabledFlag, (int)TargetType.Url, redirectUrlPage1, 1); + + // second page goes to another url (this is Tablet - it should not matter) + this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, Page2, EnabledFlag, (int)TargetType.Url, redirectUrlPage2, 1); + + var mobileUrlForPage1 = this._redirectionController.GetMobileSiteUrl(Portal0, Page1); + var mobileUrlForPage2 = this._redirectionController.GetMobileSiteUrl(Portal0, Page2); + var mobileUrlForPage3 = this._redirectionController.GetMobileSiteUrl(Portal0, Page3); + + // First Page returns link to first url + Assert.AreEqual(string.Format("{0}?nomo=0", redirectUrlPage1), mobileUrlForPage1); + + // Second Page returns link to second url + Assert.AreEqual(string.Format("{0}?nomo=0", redirectUrlPage2), mobileUrlForPage2); + + // Third Page returns link to first url - as this is the first found url and third page has no redirect defined + Assert.AreEqual(mobileUrlForPage3, string.Format("{0}?nomo=0", redirectUrlPage1)); + } + + // [Test] + // public void RedirectionController_GetMobileSiteUrl_Works_When_Page_Redirects_To_Another_Portal() + // { + // //first page goes to one second portal + // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, Portal1, 1); + + // var mobileUrlForPage1 = _redirectionController.GetMobileSiteUrl(Portal0, Page1); + + // //First Page returns link to home page of other portal + // Assert.AreEqual(Globals.AddHTTP(PortalAlias1), mobileUrlForPage1); + // } + [Test] + public void RedirectionController_GetMobileSiteUrl_When_Redirect_To_DifferentUrl() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Url, ExternalSite, 1); + + var url = this._redirectionController.GetMobileSiteUrl(Portal1, AnotherPageOnSamePortal); + + Assert.AreEqual(string.Empty, url); + } + + [Test] + public void RedirectionController_IsRedirectAllowedForTheSession_In_Normal_Action() + { + var app = this.GenerateApplication(); + + Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); + } + + [Test] + public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_1() + { + var app = this.GenerateApplication(); + app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "1"); + + Assert.IsFalse(this._redirectionController.IsRedirectAllowedForTheSession(app)); + Assert.IsNotNull(app.Request.Cookies[DisableMobileRedirectCookieName]); + Assert.IsNotNull(app.Request.Cookies[DisableRedirectPresistCookieName]); + } + + [Test] + public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_0() + { + var app = this.GenerateApplication(); + app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); + + Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); + } + + [Test] + public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_1_And_Then_Setback_To_0() + { + var app = this.GenerateApplication(); + app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "1"); + Assert.IsFalse(this._redirectionController.IsRedirectAllowedForTheSession(app)); + + app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); + Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); + } + + private void SetupContianer() + { + var serviceCollection = new ServiceCollection(); + + var mockNavigationManager = new Mock(); + mockNavigationManager.Setup(x => x.NavigateURL(It.IsAny())).Returns(x => this.NavigateUrl(x)); + var mockApplicationStatusInfo = new Mock(); mockApplicationStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.Install); serviceCollection.AddTransient(container => mockNavigationManager.Object); serviceCollection.AddTransient(container => mockApplicationStatusInfo.Object); - - Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - } - - private void SetupDataProvider() - { - this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - - this._dtRedirections = new DataTable("Redirections"); - var pkCol = this._dtRedirections.Columns.Add("Id", typeof(int)); - this._dtRedirections.Columns.Add("PortalId", typeof(int)); - this._dtRedirections.Columns.Add("Name", typeof(string)); - this._dtRedirections.Columns.Add("Type", typeof(int)); - this._dtRedirections.Columns.Add("SortOrder", typeof(int)); - this._dtRedirections.Columns.Add("SourceTabId", typeof(int)); - this._dtRedirections.Columns.Add("IncludeChildTabs", typeof(bool)); - this._dtRedirections.Columns.Add("TargetType", typeof(int)); - this._dtRedirections.Columns.Add("TargetValue", typeof(object)); - this._dtRedirections.Columns.Add("Enabled", typeof(bool)); - - this._dtRedirections.PrimaryKey = new[] { pkCol }; - - this._dtRules = new DataTable("Rules"); - var pkCol1 = this._dtRules.Columns.Add("Id", typeof(int)); - this._dtRules.Columns.Add("RedirectionId", typeof(int)); - this._dtRules.Columns.Add("Capability", typeof(string)); - this._dtRules.Columns.Add("Expression", typeof(string)); - - this._dtRules.PrimaryKey = new[] { pkCol1 }; - - this._dataProvider.Setup(d => - d.SaveRedirection( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())).Returns( - (id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled, userId) => - { - if (id == -1) - { - if (this._dtRedirections.Rows.Count == 0) - { - id = 1; - } - else - { - id = Convert.ToInt32(this._dtRedirections.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; - } - - var row = this._dtRedirections.NewRow(); - row["Id"] = id; - row["PortalId"] = portalId; - row["name"] = name; - row["type"] = type; - row["sortOrder"] = sortOrder; - row["sourceTabId"] = sourceTabId; - row["includeChildTabs"] = includeChildTabs; - row["targetType"] = targetType; - row["targetValue"] = targetValue; - row["enabled"] = enabled; - - this._dtRedirections.Rows.Add(row); - } - else - { - var rows = this._dtRedirections.Select("Id = " + id); - if (rows.Length == 1) - { - var row = rows[0]; - - row["name"] = name; - row["type"] = type; - row["sortOrder"] = sortOrder; - row["sourceTabId"] = sourceTabId; - row["includeChildTabs"] = includeChildTabs; - row["targetType"] = targetType; - row["targetValue"] = targetValue; - row["enabled"] = enabled; - } - } - - return id; - }); - - this._dataProvider.Setup(d => d.GetRedirections(It.IsAny())).Returns(this.GetRedirectionsCallBack); - this._dataProvider.Setup(d => d.DeleteRedirection(It.IsAny())).Callback((id) => - { - var rows = this._dtRedirections.Select("Id = " + id); - if (rows.Length == 1) - { - this._dtRedirections.Rows.Remove(rows[0]); - } - }); - - this._dataProvider.Setup(d => d.SaveRedirectionRule( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())).Callback((id, rid, capbility, expression) => - { - if (id == -1) - { - if (this._dtRules.Rows.Count == 0) - { - id = 1; - } - else - { - id = Convert.ToInt32(this._dtRules.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; - } - - var row = this._dtRules.NewRow(); - row["Id"] = id; - row["RedirectionId"] = rid; - row["capability"] = capbility; - row["expression"] = expression; - - this._dtRules.Rows.Add(row); - } - else - { - var rows = this._dtRules.Select("Id = " + id); - if (rows.Length == 1) - { - var row = rows[0]; - - row["capability"] = capbility; - row["expression"] = expression; - } - } - }); - - this._dataProvider.Setup(d => d.GetRedirectionRules(It.IsAny())).Returns(this.GetRedirectionRulesCallBack); - this._dataProvider.Setup(d => d.DeleteRedirectionRule(It.IsAny())).Callback((id) => - { - var rows = this._dtRules.Select("Id = " + id); - if (rows.Length == 1) - { - this._dtRules.Rows.Remove(rows[0]); - } - }); - - this._dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); - this._dataProvider.Setup(d => d.GetTabs(It.IsAny())).Returns(this.GetTabsCallBack); - this._dataProvider.Setup(d => d.GetTab(It.IsAny())).Returns(this.GetTabCallBack); - this._dataProvider.Setup(d => d.GetTabModules(It.IsAny())).Returns(this.GetTabModulesCallBack); - this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this.GetPortalSettingsCallBack); - this._dataProvider.Setup(d => d.GetAllRedirections()).Returns(this.GetAllRedirectionsCallBack); - - var portalDataService = MockComponentProvider.CreateNew(); - portalDataService.Setup(p => p.GetPortalGroups()).Returns(this.GetPortalGroupsCallBack); - } - - private void SetupClientCapabilityProvider() - { - this._clientCapabilityProvider.Setup(p => p.GetClientCapability(It.IsAny())).Returns(this.GetClientCapabilityCallBack); - } - - private void SetupRoleProvider() - { - var mockRoleProvider = MockComponentProvider.CreateNew(); - } - - private IDataReader GetRedirectionsCallBack(int portalId) - { - var dtCheck = this._dtRedirections.Clone(); - foreach (var row in this._dtRedirections.Select("PortalId = " + portalId)) - { - dtCheck.Rows.Add(row.ItemArray); - } - - return dtCheck.CreateDataReader(); - } - - private IDataReader GetRedirectionRulesCallBack(int rid) - { - var dtCheck = this._dtRules.Clone(); - foreach (var row in this._dtRules.Select("RedirectionId = " + rid)) - { - dtCheck.Rows.Add(row.ItemArray); - } - - return dtCheck.CreateDataReader(); - } - - private IDataReader GetPortalsCallBack(string culture) - { - return this.GetPortalCallBack(Portal0, DotNetNuke.Services.Localization.Localization.SystemLocale); - } - - private IDataReader GetPortalCallBack(int portalId, string culture) - { - DataTable table = new DataTable("Portal"); - - var cols = new string[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - int homePage = 55; - if (portalId == Portal0) - { - homePage = HomePageOnPortal0; - } - else if (portalId == Portal1) - { - homePage = HomePageOnPortal1; - } - - table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); - - return table.CreateDataReader(); - } - - private DataTable GetTabsDataTable() - { - DataTable table = new DataTable("Tabs"); - - var cols = new string[] - { - "TabID", "UniqueId", "VersionGuid", "DefaultLanguageGuid", "LocalizedVersionGuid", "TabOrder", "PortalID", "TabName", "IsVisible", "ParentId", "Level", "IconFile", "IconFileLarge", "DisableLink", "Title", "Description", "KeyWords", "IsDeleted", "SkinSrc", "ContainerSrc", "TabPath", "StartDate", "EndDate", "Url", "HasChildren", "RefreshInterval", "PageHeadText", "IsSecure", "PermanentRedirect", "SiteMapPriority", "ContentItemID", "Content", "ContentTypeID", "ModuleID", "ContentKey", "Indexed", "CultureCode", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "StateID", "HasBeenPublished", "IsSystem", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - table.Rows.Add(HomePageOnPortal1, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "3", Portal1, "HomePageOnPortal1", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//HomePageOnPortal1", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal1", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(HomePageOnPortal0, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "3", Portal0, "HomePageOnPortal0", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//HomePageOnPortal0", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(AnotherPageOnSamePortal, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "4", Portal0, "AnotherPageOnSamePortal", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//AnotherPageOnSamePortal", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(MobileLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "5", Portal0, "MobileLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//MobileLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(TabletLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "6", Portal0, "TabletLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//TabletLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(AllMobileLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "7", Portal0, "AllMobileLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//AllMobileLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(DeletedPageOnSamePortal, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "8", Portal0, "A Deleted Page", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, true, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//DeletedPage", null, null, string.Empty, false, null, null, false, false, "0.5", "90", "Deleted Page", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - - return table; - } - - private IDataReader GetTabsCallBack(int portalId) - { - var table = this.GetTabsDataTable(); - var newTable = table.Clone(); - foreach (var row in table.Select("PortalID = " + portalId)) - { - newTable.Rows.Add(row.ItemArray); - } - - return newTable.CreateDataReader(); - } - - private IDataReader GetTabCallBack(int tabId) - { - var table = this.GetTabsDataTable(); - var newTable = table.Clone(); - foreach (var row in table.Select("TabID = " + tabId)) - { - newTable.Rows.Add(row.ItemArray); - } - - return newTable.CreateDataReader(); - } - - private IDataReader GetTabModulesCallBack(int tabId) - { - DataTable table = new DataTable("TabModules"); - - var cols = new string[] - { - "PortalID", "TabID", "TabModuleID", "ModuleID", "ModuleDefID", "ModuleOrder", "PaneName", "ModuleTitle", "CacheTime", "CacheMethod", "Alignment", "Color", "Border", "IconFile", "AllTabs", "Visibility", "IsDeleted", "Header", "Footer", "StartDate", "EndDate", "ContainerSrc", "DisplayTitle", "DisplayPrint", "DisplaySyndicate", "IsWebSlice", "WebSliceTitle", "WebSliceExpiryDate", "WebSliceTTL", "InheritViewPermissions", "DesktopModuleID", "DefaultCacheTime", "ModuleControlID", "BusinessControllerClass", "IsAdmin", "SupportedFeatures", "ContentItemID", "Content", "ContentTypeID", "ContentKey", "Indexed", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "LastContentModifiedOnDate", "UniqueId", "VersionGuid", "DefaultLanguageGuid", "LocalizedVersionGuid", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - table.Columns["ModuleID"].DataType = typeof(int); - - var portalId = tabId == HomePageOnPortal0 ? Portal0 : Portal1; - - table.Rows.Add(portalId, tabId, 51, 362, 117, 1, "ContentPane", "DotNetNuke® Enterprise Edition", "3600", "FileModuleCachingProvider", "left", null, null, null, false, "2", false, null, null, null, null, "[G]Containers/DarkKnight/Banner.ascx", true, false, false, false, null, null, "0", true, "75", "1200", "240", "DotNetNuke.Modules.HtmlPro.HtmlTextController", false, "7", "90", "DotNetNuke® Enterprise Edition", "2", null, false, "-1", DateTime.Now, "-1", DateTime.Now, DateTime.Now, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), null); - - return table.CreateDataReader(); - } - - private IDataReader GetPortalSettingsCallBack(int portalId, string culture) - { - DataTable table = new DataTable("PortalSettings"); - - var cols = new string[] - { - "SettingName", "SettingValue", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - var alias = portalId == Portal0 ? PortalAlias0 : PortalAlias1; - - table.Rows.Add("DefaultPortalAlias", alias, "-1", DateTime.Now, "-1", DateTime.Now, "en-us"); - - return table.CreateDataReader(); - } - - private IDataReader GetPortalGroupsCallBack() - { - DataTable table = new DataTable("PortalGroups"); - - var cols = new string[] - { - "PortalGroupID", "MasterPortalID", "PortalGroupName", "PortalGroupDescription", "AuthenticationDomain", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - table.Rows.Add(1, 0, "Portal Group", string.Empty, string.Empty, -1, DateTime.Now, -1, DateTime.Now); - - return table.CreateDataReader(); - } - - private IClientCapability GetClientCapabilityCallBack(string userAgent) - { - IClientCapability clientCapability = new TestClientCapability(); - if (userAgent == iphoneUserAgent) - { - clientCapability.IsMobile = true; - clientCapability.Capabilities.Add("mobile_browser", "Safari"); - clientCapability.Capabilities.Add("device_os", "iPhone OS"); - } - else if (userAgent == iPadTabletUserAgent) - { - clientCapability.IsTablet = true; - clientCapability.Capabilities.Add("mobile_browser", "Safari"); - clientCapability.Capabilities.Add("device_os", "iPhone OS"); - } - else if (userAgent == motorolaRIZRSymbianOSOpera865) - { - clientCapability.IsMobile = true; - clientCapability.Capabilities.Add("mobile_browser", "Opera Mini"); - clientCapability.Capabilities.Add("device_os", "Symbian OS"); - } - - return clientCapability; - } - - private IDataReader GetAllRedirectionsCallBack() - { - return this._dtRedirections.CreateDataReader(); - } - - private void PrepareData() - { - // id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled - this._dtRedirections.Rows.Add(1, Portal0, "R4", (int)RedirectionType.Other, 4, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - this._dtRedirections.Rows.Add(3, Portal0, "R3", (int)RedirectionType.AllMobile, 3, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - this._dtRedirections.Rows.Add(4, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - this._dtRedirections.Rows.Add(5, Portal0, "R5", (int)RedirectionType.MobilePhone, 5, HomePageOnPortal0, EnabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - this._dtRedirections.Rows.Add(6, Portal0, "R6", (int)RedirectionType.MobilePhone, 6, -1, DisabledFlag, (int)TargetType.Tab, HomePageOnPortal0, EnabledFlag); - this._dtRedirections.Rows.Add(7, Portal0, "R7", (int)RedirectionType.MobilePhone, 7, -1, DisabledFlag, (int)TargetType.Url, ExternalSite, EnabledFlag); - - // id, redirectionId, capability, expression - this._dtRules.Rows.Add(1, 1, "mobile_browser", "Safari"); - this._dtRules.Rows.Add(2, 1, "device_os_version", "4.0"); - - this._dtRedirections.Rows.Add(8, Portal1, "R8", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); - this._dtRedirections.Rows.Add(9, Portal1, "R9", (int)RedirectionType.Tablet, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); - this._dtRedirections.Rows.Add(10, Portal1, "R10", (int)RedirectionType.AllMobile, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); - } - - private void PrepareOperaBrowserOnSymbianOSRedirectionRule() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Other, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); - - // id, redirectionId, capability, expression - this._dtRules.Rows.Add(1, 1, "mobile_browser", "Opera Mini"); - this._dtRules.Rows.Add(2, 1, "device_os", "Symbian OS"); - } - - private void PrepareOperaBrowserOnIPhoneOSRedirectionRule() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Other, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); - - // id, redirectionId, capability, expression - this._dtRules.Rows.Add(1, 1, "mobile_browser", "Opera Mini"); - this._dtRules.Rows.Add(2, 1, "device_os", "iPhone OS"); - } - - private void PreparePortalToAnotherPageOnSamePortal() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); - } - - private void PrepareSamePortalToSamePortalRedirectionRule() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Portal, Portal0, 1); - } - - private void PrepareExternalSiteRedirectionRule() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 7, -1, DisabledFlag, (int)TargetType.Url, ExternalSite, 1); - } - - private void PrepareMobileAndTabletRedirectionRuleWithMobileFirst() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Tab, MobileLandingPage, EnabledFlag); - this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, -1, DisabledFlag, (int)TargetType.Tab, TabletLandingPage, EnabledFlag); - } - - private void PrepareMobileAndTabletRedirectionRuleWithAndTabletRedirectionRuleTabletFirst() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Tablet, 1, -1, DisabledFlag, (int)TargetType.Tab, TabletLandingPage, EnabledFlag); - this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.MobilePhone, 2, -1, DisabledFlag, (int)TargetType.Tab, MobileLandingPage, EnabledFlag); - } - - private void PrepareAllMobileRedirectionRule() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.AllMobile, 1, -1, DisabledFlag, (int)TargetType.Tab, AllMobileLandingPage, EnabledFlag); - } - - private void PrepareSingleDisabledRedirectionRule() - { - this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.AllMobile, 1, -1, DisabledFlag, (int)TargetType.Tab, AllMobileLandingPage, DisabledFlag); - } - - private HttpApplication GenerateApplication() - { - var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", "c:\\"); - simulator.SimulateRequest(new Uri("http://localhost/dnn/Default.aspx")); - - var app = new HttpApplication(); - - var requestProp = typeof(NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); - requestProp.SetValue(HttpContext.Current.Request.QueryString, false, null); - - var stateProp = typeof(HttpApplication).GetField("_context", BindingFlags.Instance | BindingFlags.NonPublic); - stateProp.SetValue(app, HttpContext.Current); - - return app; - } - - private string NavigateUrl(int tabId) - { - return string.Format("/Default.aspx?tabid={0}", tabId); - } - } -} + serviceCollection.AddTransient(); + + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + private void SetupDataProvider() + { + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + this._dtRedirections = new DataTable("Redirections"); + var pkCol = this._dtRedirections.Columns.Add("Id", typeof(int)); + this._dtRedirections.Columns.Add("PortalId", typeof(int)); + this._dtRedirections.Columns.Add("Name", typeof(string)); + this._dtRedirections.Columns.Add("Type", typeof(int)); + this._dtRedirections.Columns.Add("SortOrder", typeof(int)); + this._dtRedirections.Columns.Add("SourceTabId", typeof(int)); + this._dtRedirections.Columns.Add("IncludeChildTabs", typeof(bool)); + this._dtRedirections.Columns.Add("TargetType", typeof(int)); + this._dtRedirections.Columns.Add("TargetValue", typeof(object)); + this._dtRedirections.Columns.Add("Enabled", typeof(bool)); + + this._dtRedirections.PrimaryKey = new[] { pkCol }; + + this._dtRules = new DataTable("Rules"); + var pkCol1 = this._dtRules.Columns.Add("Id", typeof(int)); + this._dtRules.Columns.Add("RedirectionId", typeof(int)); + this._dtRules.Columns.Add("Capability", typeof(string)); + this._dtRules.Columns.Add("Expression", typeof(string)); + + this._dtRules.PrimaryKey = new[] { pkCol1 }; + + this._dataProvider.Setup(d => + d.SaveRedirection( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())).Returns( + (id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled, userId) => + { + if (id == -1) + { + if (this._dtRedirections.Rows.Count == 0) + { + id = 1; + } + else + { + id = Convert.ToInt32(this._dtRedirections.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; + } + + var row = this._dtRedirections.NewRow(); + row["Id"] = id; + row["PortalId"] = portalId; + row["name"] = name; + row["type"] = type; + row["sortOrder"] = sortOrder; + row["sourceTabId"] = sourceTabId; + row["includeChildTabs"] = includeChildTabs; + row["targetType"] = targetType; + row["targetValue"] = targetValue; + row["enabled"] = enabled; + + this._dtRedirections.Rows.Add(row); + } + else + { + var rows = this._dtRedirections.Select("Id = " + id); + if (rows.Length == 1) + { + var row = rows[0]; + + row["name"] = name; + row["type"] = type; + row["sortOrder"] = sortOrder; + row["sourceTabId"] = sourceTabId; + row["includeChildTabs"] = includeChildTabs; + row["targetType"] = targetType; + row["targetValue"] = targetValue; + row["enabled"] = enabled; + } + } + + return id; + }); + + this._dataProvider.Setup(d => d.GetRedirections(It.IsAny())).Returns(this.GetRedirectionsCallBack); + this._dataProvider.Setup(d => d.DeleteRedirection(It.IsAny())).Callback((id) => + { + var rows = this._dtRedirections.Select("Id = " + id); + if (rows.Length == 1) + { + this._dtRedirections.Rows.Remove(rows[0]); + } + }); + + this._dataProvider.Setup(d => d.SaveRedirectionRule( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())).Callback((id, rid, capbility, expression) => + { + if (id == -1) + { + if (this._dtRules.Rows.Count == 0) + { + id = 1; + } + else + { + id = Convert.ToInt32(this._dtRules.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; + } + + var row = this._dtRules.NewRow(); + row["Id"] = id; + row["RedirectionId"] = rid; + row["capability"] = capbility; + row["expression"] = expression; + + this._dtRules.Rows.Add(row); + } + else + { + var rows = this._dtRules.Select("Id = " + id); + if (rows.Length == 1) + { + var row = rows[0]; + + row["capability"] = capbility; + row["expression"] = expression; + } + } + }); + + this._dataProvider.Setup(d => d.GetRedirectionRules(It.IsAny())).Returns(this.GetRedirectionRulesCallBack); + this._dataProvider.Setup(d => d.DeleteRedirectionRule(It.IsAny())).Callback((id) => + { + var rows = this._dtRules.Select("Id = " + id); + if (rows.Length == 1) + { + this._dtRules.Rows.Remove(rows[0]); + } + }); + + this._dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + this._dataProvider.Setup(d => d.GetTabs(It.IsAny())).Returns(this.GetTabsCallBack); + this._dataProvider.Setup(d => d.GetTab(It.IsAny())).Returns(this.GetTabCallBack); + this._dataProvider.Setup(d => d.GetTabModules(It.IsAny())).Returns(this.GetTabModulesCallBack); + this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this.GetPortalSettingsCallBack); + this._dataProvider.Setup(d => d.GetAllRedirections()).Returns(this.GetAllRedirectionsCallBack); + + var portalDataService = MockComponentProvider.CreateNew(); + portalDataService.Setup(p => p.GetPortalGroups()).Returns(this.GetPortalGroupsCallBack); + } + + private void SetupClientCapabilityProvider() + { + this._clientCapabilityProvider.Setup(p => p.GetClientCapability(It.IsAny())).Returns(this.GetClientCapabilityCallBack); + } + + private void SetupRoleProvider() + { + var mockRoleProvider = MockComponentProvider.CreateNew(); + } + + private IDataReader GetRedirectionsCallBack(int portalId) + { + var dtCheck = this._dtRedirections.Clone(); + foreach (var row in this._dtRedirections.Select("PortalId = " + portalId)) + { + dtCheck.Rows.Add(row.ItemArray); + } + + return dtCheck.CreateDataReader(); + } + + private IDataReader GetRedirectionRulesCallBack(int rid) + { + var dtCheck = this._dtRules.Clone(); + foreach (var row in this._dtRules.Select("RedirectionId = " + rid)) + { + dtCheck.Rows.Add(row.ItemArray); + } + + return dtCheck.CreateDataReader(); + } + + private IDataReader GetPortalsCallBack(string culture) + { + return this.GetPortalCallBack(Portal0, DotNetNuke.Services.Localization.Localization.SystemLocale); + } + + private IDataReader GetPortalCallBack(int portalId, string culture) + { + DataTable table = new DataTable("Portal"); + + var cols = new string[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + int homePage = 55; + if (portalId == Portal0) + { + homePage = HomePageOnPortal0; + } + else if (portalId == Portal1) + { + homePage = HomePageOnPortal1; + } + + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); + + return table.CreateDataReader(); + } + + private DataTable GetTabsDataTable() + { + DataTable table = new DataTable("Tabs"); + + var cols = new string[] + { + "TabID", "UniqueId", "VersionGuid", "DefaultLanguageGuid", "LocalizedVersionGuid", "TabOrder", "PortalID", "TabName", "IsVisible", "ParentId", "Level", "IconFile", "IconFileLarge", "DisableLink", "Title", "Description", "KeyWords", "IsDeleted", "SkinSrc", "ContainerSrc", "TabPath", "StartDate", "EndDate", "Url", "HasChildren", "RefreshInterval", "PageHeadText", "IsSecure", "PermanentRedirect", "SiteMapPriority", "ContentItemID", "Content", "ContentTypeID", "ModuleID", "ContentKey", "Indexed", "CultureCode", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "StateID", "HasBeenPublished", "IsSystem", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + table.Rows.Add(HomePageOnPortal1, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "3", Portal1, "HomePageOnPortal1", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//HomePageOnPortal1", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal1", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(HomePageOnPortal0, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "3", Portal0, "HomePageOnPortal0", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//HomePageOnPortal0", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(AnotherPageOnSamePortal, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "4", Portal0, "AnotherPageOnSamePortal", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//AnotherPageOnSamePortal", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(MobileLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "5", Portal0, "MobileLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//MobileLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(TabletLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "6", Portal0, "TabletLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//TabletLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(AllMobileLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "7", Portal0, "AllMobileLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//AllMobileLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(DeletedPageOnSamePortal, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "8", Portal0, "A Deleted Page", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, true, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//DeletedPage", null, null, string.Empty, false, null, null, false, false, "0.5", "90", "Deleted Page", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + + return table; + } + + private IDataReader GetTabsCallBack(int portalId) + { + var table = this.GetTabsDataTable(); + var newTable = table.Clone(); + foreach (var row in table.Select("PortalID = " + portalId)) + { + newTable.Rows.Add(row.ItemArray); + } + + return newTable.CreateDataReader(); + } + + private IDataReader GetTabCallBack(int tabId) + { + var table = this.GetTabsDataTable(); + var newTable = table.Clone(); + foreach (var row in table.Select("TabID = " + tabId)) + { + newTable.Rows.Add(row.ItemArray); + } + + return newTable.CreateDataReader(); + } + + private IDataReader GetTabModulesCallBack(int tabId) + { + DataTable table = new DataTable("TabModules"); + + var cols = new string[] + { + "PortalID", "TabID", "TabModuleID", "ModuleID", "ModuleDefID", "ModuleOrder", "PaneName", "ModuleTitle", "CacheTime", "CacheMethod", "Alignment", "Color", "Border", "IconFile", "AllTabs", "Visibility", "IsDeleted", "Header", "Footer", "StartDate", "EndDate", "ContainerSrc", "DisplayTitle", "DisplayPrint", "DisplaySyndicate", "IsWebSlice", "WebSliceTitle", "WebSliceExpiryDate", "WebSliceTTL", "InheritViewPermissions", "DesktopModuleID", "DefaultCacheTime", "ModuleControlID", "BusinessControllerClass", "IsAdmin", "SupportedFeatures", "ContentItemID", "Content", "ContentTypeID", "ContentKey", "Indexed", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "LastContentModifiedOnDate", "UniqueId", "VersionGuid", "DefaultLanguageGuid", "LocalizedVersionGuid", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + table.Columns["ModuleID"].DataType = typeof(int); + + var portalId = tabId == HomePageOnPortal0 ? Portal0 : Portal1; + + table.Rows.Add(portalId, tabId, 51, 362, 117, 1, "ContentPane", "DotNetNuke® Enterprise Edition", "3600", "FileModuleCachingProvider", "left", null, null, null, false, "2", false, null, null, null, null, "[G]Containers/DarkKnight/Banner.ascx", true, false, false, false, null, null, "0", true, "75", "1200", "240", "DotNetNuke.Modules.HtmlPro.HtmlTextController", false, "7", "90", "DotNetNuke® Enterprise Edition", "2", null, false, "-1", DateTime.Now, "-1", DateTime.Now, DateTime.Now, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), null); + + return table.CreateDataReader(); + } + + private IDataReader GetPortalSettingsCallBack(int portalId, string culture) + { + DataTable table = new DataTable("PortalSettings"); + + var cols = new string[] + { + "SettingName", "SettingValue", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + var alias = portalId == Portal0 ? PortalAlias0 : PortalAlias1; + + table.Rows.Add("DefaultPortalAlias", alias, "-1", DateTime.Now, "-1", DateTime.Now, "en-us"); + + return table.CreateDataReader(); + } + + private IDataReader GetPortalGroupsCallBack() + { + DataTable table = new DataTable("PortalGroups"); + + var cols = new string[] + { + "PortalGroupID", "MasterPortalID", "PortalGroupName", "PortalGroupDescription", "AuthenticationDomain", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + table.Rows.Add(1, 0, "Portal Group", string.Empty, string.Empty, -1, DateTime.Now, -1, DateTime.Now); + + return table.CreateDataReader(); + } + + private IClientCapability GetClientCapabilityCallBack(string userAgent) + { + IClientCapability clientCapability = new TestClientCapability(); + if (userAgent == iphoneUserAgent) + { + clientCapability.IsMobile = true; + clientCapability.Capabilities.Add("mobile_browser", "Safari"); + clientCapability.Capabilities.Add("device_os", "iPhone OS"); + } + else if (userAgent == iPadTabletUserAgent) + { + clientCapability.IsTablet = true; + clientCapability.Capabilities.Add("mobile_browser", "Safari"); + clientCapability.Capabilities.Add("device_os", "iPhone OS"); + } + else if (userAgent == motorolaRIZRSymbianOSOpera865) + { + clientCapability.IsMobile = true; + clientCapability.Capabilities.Add("mobile_browser", "Opera Mini"); + clientCapability.Capabilities.Add("device_os", "Symbian OS"); + } + + return clientCapability; + } + + private IDataReader GetAllRedirectionsCallBack() + { + return this._dtRedirections.CreateDataReader(); + } + + private void PrepareData() + { + // id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled + this._dtRedirections.Rows.Add(1, Portal0, "R4", (int)RedirectionType.Other, 4, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(3, Portal0, "R3", (int)RedirectionType.AllMobile, 3, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(4, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(5, Portal0, "R5", (int)RedirectionType.MobilePhone, 5, HomePageOnPortal0, EnabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(6, Portal0, "R6", (int)RedirectionType.MobilePhone, 6, -1, DisabledFlag, (int)TargetType.Tab, HomePageOnPortal0, EnabledFlag); + this._dtRedirections.Rows.Add(7, Portal0, "R7", (int)RedirectionType.MobilePhone, 7, -1, DisabledFlag, (int)TargetType.Url, ExternalSite, EnabledFlag); + + // id, redirectionId, capability, expression + this._dtRules.Rows.Add(1, 1, "mobile_browser", "Safari"); + this._dtRules.Rows.Add(2, 1, "device_os_version", "4.0"); + + this._dtRedirections.Rows.Add(8, Portal1, "R8", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); + this._dtRedirections.Rows.Add(9, Portal1, "R9", (int)RedirectionType.Tablet, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); + this._dtRedirections.Rows.Add(10, Portal1, "R10", (int)RedirectionType.AllMobile, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); + } + + private void PrepareOperaBrowserOnSymbianOSRedirectionRule() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Other, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); + + // id, redirectionId, capability, expression + this._dtRules.Rows.Add(1, 1, "mobile_browser", "Opera Mini"); + this._dtRules.Rows.Add(2, 1, "device_os", "Symbian OS"); + } + + private void PrepareOperaBrowserOnIPhoneOSRedirectionRule() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Other, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); + + // id, redirectionId, capability, expression + this._dtRules.Rows.Add(1, 1, "mobile_browser", "Opera Mini"); + this._dtRules.Rows.Add(2, 1, "device_os", "iPhone OS"); + } + + private void PreparePortalToAnotherPageOnSamePortal() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); + } + + private void PrepareSamePortalToSamePortalRedirectionRule() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Portal, Portal0, 1); + } + + private void PrepareExternalSiteRedirectionRule() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 7, -1, DisabledFlag, (int)TargetType.Url, ExternalSite, 1); + } + + private void PrepareMobileAndTabletRedirectionRuleWithMobileFirst() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Tab, MobileLandingPage, EnabledFlag); + this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, -1, DisabledFlag, (int)TargetType.Tab, TabletLandingPage, EnabledFlag); + } + + private void PrepareMobileAndTabletRedirectionRuleWithAndTabletRedirectionRuleTabletFirst() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Tablet, 1, -1, DisabledFlag, (int)TargetType.Tab, TabletLandingPage, EnabledFlag); + this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.MobilePhone, 2, -1, DisabledFlag, (int)TargetType.Tab, MobileLandingPage, EnabledFlag); + } + + private void PrepareAllMobileRedirectionRule() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.AllMobile, 1, -1, DisabledFlag, (int)TargetType.Tab, AllMobileLandingPage, EnabledFlag); + } + + private void PrepareSingleDisabledRedirectionRule() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.AllMobile, 1, -1, DisabledFlag, (int)TargetType.Tab, AllMobileLandingPage, DisabledFlag); + } + + private HttpApplication GenerateApplication() + { + var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", "c:\\"); + simulator.SimulateRequest(new Uri("http://localhost/dnn/Default.aspx")); + + var app = new HttpApplication(); + + var requestProp = typeof(NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); + requestProp.SetValue(HttpContext.Current.Request.QueryString, false, null); + + var stateProp = typeof(HttpApplication).GetField("_context", BindingFlags.Instance | BindingFlags.NonPublic); + stateProp.SetValue(app, HttpContext.Current); + + return app; + } + + private string NavigateUrl(int tabId) + { + return string.Format("/Default.aspx?tabid={0}", tabId); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/TokenReplaceTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/TokenReplaceTests.cs index 6182dd77dac..cc1049aeeb0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/TokenReplaceTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/TokenReplaceTests.cs @@ -1,121 +1,134 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Services.Tokens -{ +namespace DotNetNuke.Tests.Core.Services.Tokens +{ + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; using DotNetNuke.ComponentModel; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Modules.Actions; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Tabs; - using DotNetNuke.Entities.Users; - using DotNetNuke.Services.Cache; - using DotNetNuke.Services.Tokens; - using DotNetNuke.Tests.Utilities.Mocks; - using Moq; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Tokens; + using DotNetNuke.Tests.Utilities.Mocks; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + using NUnit.Framework; - [TestFixture] - public class TokenReplaceTests - { - private Mock _mockCache; - private Mock _portalController; - private Mock _moduleController; - private Mock _userController; - private Mock _mockHostController; - - [SetUp] - public void SetUp() - { - ComponentFactory.RegisterComponentInstance(new CoreTokenProvider()); - this._mockCache = MockComponentProvider.CreateDataCacheProvider(); - this._mockHostController = new Mock(); - this._portalController = new Mock(); - this._moduleController = new Mock(); - this._userController = new Mock(); - PortalController.SetTestableInstance(this._portalController.Object); - ModuleController.SetTestableInstance(this._moduleController.Object); - UserController.SetTestableInstance(this._userController.Object); - HostController.RegisterInstance(this._mockHostController.Object); - this.SetupPortalSettings(); - this.SetupModuleInfo(); - this.SetupUserInfo(); - } - - [TearDown] - public void TearDown() - { - PortalController.ClearInstance(); - ModuleController.ClearInstance(); - UserController.ClearInstance(); - } - - [Test] - [TestCase("var myArray = [{ foo: 'bar' }]")] - [TestCase("This is just plain text")] - public void TextInputIsReturnedUnModified(string sourceText) - { - // Arrange - var tokenReplace = new TokenReplace(Scope.DefaultSettings, PortalSettings.Current.DefaultLanguage, - PortalSettings.Current, UserController.Instance.GetUser(1, 1), 1); - - // Act - var outputText = tokenReplace.ReplaceEnvironmentTokens(sourceText); - - // Assert - Assert.AreEqual(outputText, sourceText); - } - - [Test] - [TestCase("[Resx:{key:\"Email\"}]")] - [TestCase("[Css: { path: \"~/DesktopModules/Dnn/ContactList/stylesheets/bootstrap.min.css\"}]")] - [TestCase("[JavaScript:{ jsname: \"Knockout\" }] [JavaScript:{ path: \"~/DesktopModules/Dnn/ContactList/ClientScripts/contacts.js\"}]")] - public void ObjectInputIsReturnedBlank(string sourceText) - { - // Arrange - var tokenReplace = new TokenReplace(Scope.DefaultSettings, PortalSettings.Current.DefaultLanguage, - PortalSettings.Current, UserController.Instance.GetUser(1, 1), 1); - - // Act - var outputText = tokenReplace.ReplaceEnvironmentTokens(sourceText); - - // Assert - Assert.AreEqual(outputText.Trim(), string.Empty); - } - - private void SetupPortalSettings() - { - var portalSettings = new PortalSettings - { - AdministratorRoleName = Utilities.Constants.RoleName_Administrators, - ActiveTab = new TabInfo { ModuleID = 1, TabID = 1 }, - }; - - this._portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); - } - - private void SetupModuleInfo() - { - var moduleInfo = new ModuleInfo - { - ModuleID = 1, - PortalID = this._portalController.Object.GetCurrentPortalSettings().PortalId, - }; - - this._moduleController.Setup(mc => mc.GetModule(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(moduleInfo); - } - - private void SetupUserInfo() - { - var userInfo = new UserInfo - { - UserID = 1, - Username = "admin", - PortalID = this._portalController.Object.GetCurrentPortalSettings().PortalId, - }; - this._userController.Setup(uc => uc.GetUser(It.IsAny(), It.IsAny())).Returns(userInfo); - } - } -} + [TestFixture] + public class TokenReplaceTests + { + private Mock mockCache; + private Mock portalController; + private Mock moduleController; + private Mock userController; + private Mock mockHostController; + + [SetUp] + public void SetUp() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + + ComponentFactory.RegisterComponentInstance(new CoreTokenProvider()); + this.mockCache = MockComponentProvider.CreateDataCacheProvider(); + this.mockHostController = new Mock(); + this.portalController = new Mock(); + this.moduleController = new Mock(); + this.userController = new Mock(); + PortalController.SetTestableInstance(this.portalController.Object); + ModuleController.SetTestableInstance(this.moduleController.Object); + UserController.SetTestableInstance(this.userController.Object); + HostController.RegisterInstance(this.mockHostController.Object); + this.SetupPortalSettings(); + this.SetupModuleInfo(); + this.SetupUserInfo(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + PortalController.ClearInstance(); + ModuleController.ClearInstance(); + UserController.ClearInstance(); + } + + [Test] + [TestCase("var myArray = [{ foo: 'bar' }]")] + [TestCase("This is just plain text")] + public void TextInputIsReturnedUnModified(string sourceText) + { + // Arrange + var tokenReplace = new TokenReplace(Scope.DefaultSettings, PortalSettings.Current.DefaultLanguage, + PortalSettings.Current, UserController.Instance.GetUser(1, 1), 1); + + // Act + var outputText = tokenReplace.ReplaceEnvironmentTokens(sourceText); + + // Assert + Assert.AreEqual(outputText, sourceText); + } + + [Test] + [TestCase("[Resx:{key:\"Email\"}]")] + [TestCase("[Css: { path: \"~/DesktopModules/Dnn/ContactList/stylesheets/bootstrap.min.css\"}]")] + [TestCase("[JavaScript:{ jsname: \"Knockout\" }] [JavaScript:{ path: \"~/DesktopModules/Dnn/ContactList/ClientScripts/contacts.js\"}]")] + public void ObjectInputIsReturnedBlank(string sourceText) + { + // Arrange + var tokenReplace = new TokenReplace(Scope.DefaultSettings, PortalSettings.Current.DefaultLanguage, + PortalSettings.Current, UserController.Instance.GetUser(1, 1), 1); + + // Act + var outputText = tokenReplace.ReplaceEnvironmentTokens(sourceText); + + // Assert + Assert.AreEqual(outputText.Trim(), string.Empty); + } + + private void SetupPortalSettings() + { + var portalSettings = new PortalSettings + { + AdministratorRoleName = Utilities.Constants.RoleName_Administrators, + ActiveTab = new TabInfo { ModuleID = 1, TabID = 1 }, + }; + + this.portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); + } + + private void SetupModuleInfo() + { + var moduleInfo = new ModuleInfo + { + ModuleID = 1, + PortalID = this.portalController.Object.GetCurrentPortalSettings().PortalId, + }; + + this.moduleController.Setup(mc => mc.GetModule(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(moduleInfo); + } + + private void SetupUserInfo() + { + var userInfo = new UserInfo + { + UserID = 1, + Username = "admin", + PortalID = this.portalController.Object.GetCurrentPortalSettings().PortalId, + }; + this.userController.Setup(uc => uc.GetUser(It.IsAny(), It.IsAny())).Returns(userInfo); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UserRequest/UserRequestIPAddressControllerTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UserRequest/UserRequestIPAddressControllerTest.cs index 19260665959..5ef455fb891 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UserRequest/UserRequestIPAddressControllerTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UserRequest/UserRequestIPAddressControllerTest.cs @@ -2,128 +2,143 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Core.Services.UserRequest -{ - using System.Collections.Specialized; - using System.Web; - - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Services.UserRequest; - using DotNetNuke.Tests.Utilities; - using DotNetNuke.Tests.Utilities.Mocks; - using Moq; - using NUnit.Framework; - - [TestFixture] - internal class UserRequestIPAddressControllerTest - { - private Mock _mockPortalController; - private Mock _mockHostController; - private Mock _mockhttpContext; - private Mock _mockRequest; - - private UserRequestIPAddressController _userRequestIPAddressController; - - [SetUp] - public void Setup() - { - NameValueCollection serverVariables = new NameValueCollection(); - - // Setup Mock - this._mockhttpContext = HttpContextHelper.RegisterMockHttpContext(); - this._mockRequest = Mock.Get(this._mockhttpContext.Object.Request); - this._mockRequest.Setup(x => x.ServerVariables).Returns(serverVariables); - this._mockHostController = MockComponentProvider.CreateNew(); - this._mockPortalController = MockComponentProvider.CreateNew(); - PortalController.SetTestableInstance(this._mockPortalController.Object); - - // System under test - this._userRequestIPAddressController = new UserRequestIPAddressController(); - } - - [TearDown] - public void TearDown() - { - MockComponentProvider.ResetContainer(); - } - - [TestCase("111.111.111.111", "X-Forwarded-For")] - [TestCase("111.111.111.111,123.112.11.33", "X-Forwarded-For")] - [TestCase("111.111.111.111", "X-ProxyUser-Ip")] - [TestCase("111.111.111.111,23.112.11.33", "X-ProxyUser-Ip")] - public void UserRequestIPAddress_ShouldReturnIP_IfAnyHeaderIsPresent(string requestIp, string headerName) - { - // Arrange - var expectedIp = "111.111.111.111"; - - NameValueCollection headersWithXForwardedHeaders = new NameValueCollection(); - headersWithXForwardedHeaders.Add(headerName, requestIp); - this._mockHostController.Setup(hc => hc.GetString(It.IsAny(), It.IsAny())).Returns(headerName); - this._mockRequest.Setup(x => x.Headers).Returns(headersWithXForwardedHeaders); - - // Act - string userRequestIPAddress = this._userRequestIPAddressController.GetUserRequestIPAddress(this._mockhttpContext.Object.Request); - - // Assert - Assert.AreEqual(expectedIp, userRequestIPAddress); - } - - [Test] - public void UserRequestIPAddress_ShouldReturnIP_IfRemoteAddrServerVariablePresent() - { - // Arrange - var expectedIp = "111.111.111.111"; - var remoteVariable = "REMOTE_ADDR"; - var requestIp = "111.111.111.111"; - - NameValueCollection serverVariables = new NameValueCollection(); - serverVariables.Add(remoteVariable, requestIp); - this._mockRequest.Setup(x => x.ServerVariables).Returns(serverVariables); - - // Act - var userRequestIPAddress = this._userRequestIPAddressController.GetUserRequestIPAddress(this._mockhttpContext.Object.Request); - - // Assert - Assert.AreSame(expectedIp, userRequestIPAddress); - this._mockRequest.VerifyGet(r => r.ServerVariables); - this._mockRequest.VerifyGet(r => r.Headers); - this._mockHostController.Verify(hc => hc.GetString(It.IsAny(), It.IsAny())); - } - - [Test] - public void UserRequestIPAddress_ShouldReturnIP_IfUserHostAddress() - { - // Arrange - var expectedIp = "111.111.111.111"; - this._mockRequest.Setup(x => x.UserHostAddress).Returns(expectedIp); - - // Act - var userRequestIPAddress = this._userRequestIPAddressController.GetUserRequestIPAddress(this._mockhttpContext.Object.Request); - - // Assert - Assert.AreSame(expectedIp, userRequestIPAddress); - this._mockRequest.VerifyGet(r => r.UserHostAddress); - } - - [TestCase("abc.111.eer")] - [TestCase("somedomain.com")] - [TestCase("244.275.111.111")] - public void UserRequestIPAddress_ShouldReturnEmptyString_IfIPAddressIsNotValid(string requestIp) - { - // Arrange - var headerName = "X-Forwarded-For"; - - NameValueCollection headersWithXForwardedHeaders = new NameValueCollection(); - headersWithXForwardedHeaders.Add(headerName, requestIp); - this._mockRequest.Setup(x => x.Headers).Returns(headersWithXForwardedHeaders); - this._mockHostController.Setup(hc => hc.GetString(It.IsAny(), It.IsAny())).Returns(headerName); - - // Act - var userRequestIPAddress = this._userRequestIPAddressController.GetUserRequestIPAddress(this._mockhttpContext.Object.Request); - - // Assert - Assert.AreSame(string.Empty, userRequestIPAddress); - } - } -} +namespace DotNetNuke.Tests.Core.Services.UserRequest +{ + using System.Collections.Specialized; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.UserRequest; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + internal class UserRequestIPAddressControllerTest + { + private Mock mockPortalController; + private Mock mockHostController; + private Mock mockhttpContext; + private Mock mockRequest; + + private UserRequestIPAddressController userRequestIPAddressController; + + [SetUp] + public void Setup() + { + NameValueCollection serverVariables = new NameValueCollection(); + + // Setup Mock + this.mockhttpContext = HttpContextHelper.RegisterMockHttpContext(); + this.mockRequest = Mock.Get(this.mockhttpContext.Object.Request); + this.mockRequest.Setup(x => x.ServerVariables).Returns(serverVariables); + this.mockHostController = new Mock(); + this.mockHostController.As(); + this.mockPortalController = MockComponentProvider.CreateNew(); + PortalController.SetTestableInstance(this.mockPortalController.Object); + + // System under test + this.userRequestIPAddressController = new UserRequestIPAddressController(); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => (IHostSettingsService)this.mockHostController.Object); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [TearDown] + public void TearDown() + { + Globals.DependencyProvider = null; + MockComponentProvider.ResetContainer(); + } + + [TestCase("111.111.111.111", "X-Forwarded-For")] + [TestCase("111.111.111.111,123.112.11.33", "X-Forwarded-For")] + [TestCase("111.111.111.111", "X-ProxyUser-Ip")] + [TestCase("111.111.111.111,23.112.11.33", "X-ProxyUser-Ip")] + public void UserRequestIPAddress_ShouldReturnIP_IfAnyHeaderIsPresent(string requestIp, string headerName) + { + // Arrange + var expectedIp = "111.111.111.111"; + + NameValueCollection headersWithXForwardedHeaders = new NameValueCollection(); + headersWithXForwardedHeaders.Add(headerName, requestIp); + this.mockHostController.Setup(hc => hc.GetString(It.IsAny(), It.IsAny())).Returns(headerName); + this.mockRequest.Setup(x => x.Headers).Returns(headersWithXForwardedHeaders); + + // Act + string userRequestIPAddress = this.userRequestIPAddressController.GetUserRequestIPAddress(this.mockhttpContext.Object.Request); + + // Assert + Assert.AreEqual(expectedIp, userRequestIPAddress); + } + + [Test] + public void UserRequestIPAddress_ShouldReturnIP_IfRemoteAddrServerVariablePresent() + { + // Arrange + var expectedIp = "111.111.111.111"; + var remoteVariable = "REMOTE_ADDR"; + var requestIp = "111.111.111.111"; + + NameValueCollection serverVariables = new NameValueCollection(); + serverVariables.Add(remoteVariable, requestIp); + this.mockRequest.Setup(x => x.ServerVariables).Returns(serverVariables); + + // Act + var userRequestIPAddress = this.userRequestIPAddressController.GetUserRequestIPAddress(this.mockhttpContext.Object.Request); + + // Assert + Assert.AreSame(expectedIp, userRequestIPAddress); + this.mockRequest.VerifyGet(r => r.ServerVariables); + this.mockRequest.VerifyGet(r => r.Headers); + this.mockHostController.Verify(hc => hc.GetString(It.IsAny(), It.IsAny())); + } + + [Test] + public void UserRequestIPAddress_ShouldReturnIP_IfUserHostAddress() + { + // Arrange + var expectedIp = "111.111.111.111"; + this.mockRequest.Setup(x => x.UserHostAddress).Returns(expectedIp); + + // Act + var userRequestIPAddress = this.userRequestIPAddressController.GetUserRequestIPAddress(this.mockhttpContext.Object.Request); + + // Assert + Assert.AreSame(expectedIp, userRequestIPAddress); + this.mockRequest.VerifyGet(r => r.UserHostAddress); + } + + [TestCase("abc.111.eer")] + [TestCase("somedomain.com")] + [TestCase("244.275.111.111")] + public void UserRequestIPAddress_ShouldReturnEmptyString_IfIPAddressIsNotValid(string requestIp) + { + // Arrange + var headerName = "X-Forwarded-For"; + + NameValueCollection headersWithXForwardedHeaders = new NameValueCollection(); + headersWithXForwardedHeaders.Add(headerName, requestIp); + this.mockRequest.Setup(x => x.Headers).Returns(headersWithXForwardedHeaders); + this.mockHostController.Setup(hc => hc.GetString(It.IsAny(), It.IsAny())).Returns(headerName); + + // Act + var userRequestIPAddress = this.userRequestIPAddressController.GetUserRequestIPAddress(this.mockhttpContext.Object.Request); + + // Assert + Assert.AreSame(string.Empty, userRequestIPAddress); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs index 15a2a50c38d..f31e5a6beb7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs @@ -11,6 +11,7 @@ namespace DotNetNuke.Tests.Web.Api using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; + using DotNetNuke.Abstractions.Portals; using DotNetNuke.Common; using DotNetNuke.Common.Internal; using DotNetNuke.Entities.Portals; @@ -24,27 +25,36 @@ namespace DotNetNuke.Tests.Web.Api [TestFixture] public class PortalAliasRouteManagerTests - { + { + private Mock mockPortalAliasService; + [SetUp] public void SetUp() { var services = new ServiceCollection(); var navigationManagerMock = new Mock(); + var mockApplicationStatusInfo = new Mock(); mockApplicationStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.Install); + this.mockPortalAliasService = new Mock(); + this.mockPortalAliasService.As(); + services.AddTransient(container => mockApplicationStatusInfo.Object); services.AddScoped(typeof(INavigationManager), (x) => navigationManagerMock.Object); - + services.AddScoped(_ => this.mockPortalAliasService.Object); + Globals.DependencyProvider = services.BuildServiceProvider(); } [TearDown] public void TearDown() { - Globals.DependencyProvider = null; + Globals.DependencyProvider = null; + + this.mockPortalAliasService = null; + PortalController.ClearInstance(); - PortalAliasController.ClearInstance(); TestableGlobals.ClearInstance(); } @@ -97,13 +107,15 @@ public void ParentPortalOnVirtualDirReturnsAnEmptyPrefix() var portals = new ArrayList { new PortalInfo { PortalID = 1 } }; mockPortalController.Setup(x => x.GetPortals()).Returns(portals); PortalController.SetTestableInstance(mockPortalController.Object); - - var mockPortalAliasController = new Mock(); - mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] + + this.mockPortalAliasService.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir" } }); - PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); + this.mockPortalAliasService.As().Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] + { + new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir" } + }); var mockGlobals = new Mock(); mockGlobals.Setup(x => x.ApplicationPath).Returns("/vdir"); @@ -125,12 +137,14 @@ public void SingleParentPortalReturnsAnEmptyPrefix() mockPortalController.Setup(x => x.GetPortals()).Returns(portals); PortalController.SetTestableInstance(mockPortalController.Object); - var mockPortalAliasController = new Mock(); - mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] + this.mockPortalAliasService.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] + { + new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } + }); + this.mockPortalAliasService.As().Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } }); - PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); var mockGlobals = new Mock(); mockGlobals.Setup(x => x.ApplicationPath).Returns(string.Empty); @@ -151,10 +165,9 @@ public void PrefixCountsAreCached() var portals = new ArrayList { new PortalInfo { PortalID = 1 } }; mockPortalController.Setup(x => x.GetPortals()).Returns(portals); PortalController.SetTestableInstance(mockPortalController.Object); - - var mockPortalAliasController = new Mock(); - mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } }); - PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); + + this.mockPortalAliasService.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } }); + this.mockPortalAliasService.As().Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } }); var mockGlobals = new Mock(); mockGlobals.Setup(x => x.ApplicationPath).Returns(string.Empty); @@ -178,9 +191,8 @@ public void PrefixCountsCacheCanBeCleared() mockPortalController.Setup(x => x.GetPortals()).Returns(portals); PortalController.SetTestableInstance(mockPortalController.Object); - var mockPortalAliasController = new Mock(); - mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } }); - PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); + this.mockPortalAliasService.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } }); + this.mockPortalAliasService.As().Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } }); var mockGlobals = new Mock(); mockGlobals.Setup(x => x.ApplicationPath).Returns(string.Empty); @@ -205,13 +217,17 @@ public void VirtralDirWithChildPortalHasABlankAndASinglePrefix() mockPortalController.Setup(x => x.GetPortals()).Returns(portals); PortalController.SetTestableInstance(mockPortalController.Object); - var mockPortalAliasController = new Mock(); - mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] + this.mockPortalAliasService.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] + { + new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir" }, + new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir/child" }, + }); + this.mockPortalAliasService.As() + .Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir" }, new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir/child" }, }); - PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); var mockGlobals = new Mock(); mockGlobals.Setup(x => x.ApplicationPath).Returns("/vdir"); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs index a38296883e1..480c2bf1bde 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs @@ -12,6 +12,7 @@ namespace DotNetNuke.Tests.Web.Api using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; + using DotNetNuke.Abstractions.Portals; using DotNetNuke.Common; using DotNetNuke.Entities.Portals; using DotNetNuke.Framework.Internal.Reflection; @@ -26,28 +27,37 @@ namespace DotNetNuke.Tests.Web.Api public class ServiceRoutingManagerTests { // ReSharper disable UnusedMember.Local - private readonly List _emptyStringArrays = new List + private readonly List emptyStringArrays = new List { null, new string[0], new[] { string.Empty }, new string[] { null } }; // ReSharper restore UnusedMember.Local - private Mock _mockPortalController; - private IPortalController _portalController; + private Mock mockPortalController; + private IPortalController portalController; + + private Mock mockPortalAliasService; [SetUp] public void Setup() { FakeServiceRouteMapper.RegistrationCalls = 0; - this._mockPortalController = new Mock(); - this._portalController = this._mockPortalController.Object; - PortalController.SetTestableInstance(this._portalController); + this.mockPortalController = new Mock(); + this.portalController = this.mockPortalController.Object; + PortalController.SetTestableInstance(this.portalController); var services = new ServiceCollection(); var navigationManagerMock = new Mock(); + var mockApplicationStatusInfo = new Mock(); mockApplicationStatusInfo.Setup(info => info.Status).Returns(UpgradeStatus.Install); + + this.mockPortalAliasService = new Mock(); + this.mockPortalAliasService.As(); + services.AddTransient(container => mockApplicationStatusInfo.Object); services.AddScoped(typeof(INavigationManager), (x) => navigationManagerMock.Object); + services.AddScoped(_ => this.mockPortalAliasService.Object); + Globals.DependencyProvider = services.BuildServiceProvider(); } @@ -62,6 +72,7 @@ public void TearDown() } Globals.DependencyProvider = null; + this.mockPortalAliasService = null; } [Test] @@ -92,7 +103,7 @@ public void LocatesAllServiceRouteMappers() } [Test] - public void NameSpaceRequiredOnMapRouteCalls([ValueSource("_emptyStringArrays")] string[] namespaces) + public void NameSpaceRequiredOnMapRouteCalls([ValueSource("emptyStringArrays")] string[] namespaces) { var srm = new ServicesRoutingManager(new RouteCollection()); @@ -150,7 +161,7 @@ public void UniqueNameRequiredOnMapRouteCalls(string uniqueName) public void UrlCanStartWithSlash() { // Arrange - this._mockPortalController.Setup(x => x.GetPortals()).Returns(new ArrayList()); + this.mockPortalController.Setup(x => x.GetPortals()).Returns(new ArrayList()); // Act var srm = new ServicesRoutingManager(new RouteCollection()); @@ -164,10 +175,10 @@ public void NameIsInsertedInRouteDataTokens() { // Arrange var portalInfo = new ArrayList { new PortalInfo { PortalID = 0 } }; - this._mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); - var mockPac = new Mock(); - mockPac.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); - PortalAliasController.SetTestableInstance(mockPac.Object); + this.mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); + + this.mockPortalAliasService.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); + this.mockPortalAliasService.As().Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); var routeCollection = new RouteCollection(); var srm = new ServicesRoutingManager(routeCollection); @@ -185,10 +196,10 @@ public void TwoRoutesOnTheSameFolderHaveSimilarNames() { // Arrange var portalInfo = new ArrayList { new PortalInfo { PortalID = 0 } }; - this._mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); - var mockPac = new Mock(); - mockPac.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); - PortalAliasController.SetTestableInstance(mockPac.Object); + this.mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); + + this.mockPortalAliasService.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); + this.mockPortalAliasService.As().Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); var routeCollection = new RouteCollection(); var srm = new ServicesRoutingManager(routeCollection); @@ -209,10 +220,10 @@ public void RoutesShouldHaveBackwardCompability() { // Arrange var portalInfo = new ArrayList { new PortalInfo { PortalID = 0 } }; - this._mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); - var mockPac = new Mock(); - mockPac.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); - PortalAliasController.SetTestableInstance(mockPac.Object); + this.mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); + + this.mockPortalAliasService.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); + this.mockPortalAliasService.As().Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); var routeCollection = new RouteCollection(); var srm = new ServicesRoutingManager(routeCollection); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs index 875786e47d6..3264a5adb08 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs @@ -12,6 +12,7 @@ namespace DotNetNuke.Tests.Web.InternalServices using System.Net.Http; using System.Web.Http; using System.Web.Http.Hosting; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Common; @@ -32,8 +33,11 @@ namespace DotNetNuke.Tests.Web.InternalServices using DotNetNuke.Web.Api; using DotNetNuke.Web.InternalServices; using DotNetNuke.Web.InternalServices.Views.Search; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using NUnit.Framework; using Constants = DotNetNuke.Services.Search.Internals.Constants; @@ -78,19 +82,19 @@ public class SearchServiceControllerTests private const string SearchIndexFolder = @"App_Data\SearchTests"; private const int DefaultSearchRetryTimes = 5; - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - private Mock _mockCBO; - private Mock _mockHostController; - private Mock _mockCachingProvider; - private Mock _mockDataProvider; - private Mock _mockLocaleController; - private Mock _mockDataService; - private Mock _mockUserController; - private Mock _mockModuleController; - private Mock _mockTabController; - private SearchServiceController _searchServiceController; - private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; + private readonly double readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; + private Mock mockCBO; + private Mock mockHostController; + private Mock mockCachingProvider; + private Mock mockDataProvider; + private Mock mockLocaleController; + private Mock mockDataService; + private Mock mockUserController; + private Mock mockModuleController; + private Mock mockTabController; + private SearchServiceController searchServiceController; + private IInternalSearchController internalSearchController; + private LuceneControllerImpl luceneController; [SetUp] public void SetUp() @@ -102,16 +106,17 @@ public void SetUp() var serviceCollection = new ServiceCollection(); serviceCollection.AddTransient(container => new DotNetNuke.Application.ApplicationStatusInfo(Mock.Of())); serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(); Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); - this._mockDataProvider = MockComponentProvider.CreateDataProvider(); - this._mockLocaleController = MockComponentProvider.CreateLocaleController(); - this._mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - this._mockDataService = new Mock(); - this._mockUserController = new Mock(); - this._mockModuleController = new Mock(); - this._mockTabController = new Mock(); - this._mockHostController = new Mock(); + this.mockDataProvider = MockComponentProvider.CreateDataProvider(); + this.mockLocaleController = MockComponentProvider.CreateLocaleController(); + this.mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); + this.mockDataService = new Mock(); + this.mockUserController = new Mock(); + this.mockModuleController = new Mock(); + this.mockTabController = new Mock(); + this.mockHostController = new Mock(); this.SetupDataProvider(); this.SetupHostController(); @@ -120,15 +125,15 @@ public void SetUp() this.SetupModuleController(); this.DeleteIndexFolder(); - TabController.SetTestableInstance(this._mockTabController.Object); - this._internalSearchController = InternalSearchController.Instance; + TabController.SetTestableInstance(this.mockTabController.Object); + this.internalSearchController = InternalSearchController.Instance; - this._mockCBO = new Mock(); + this.mockCBO = new Mock(); var tabKey = string.Format("{0}-{1}", TabSearchTypeId, 0); var userKey = string.Format("{0}-{1}", UserSearchTypeId, 0); - this._mockCBO.Setup(c => c.GetCachedObject>(It.IsAny(), It.IsAny(), It.IsAny())) + this.mockCBO.Setup(c => c.GetCachedObject>(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new Dictionary() { { tabKey, TabSearchTypeName }, { userKey, UserSearchTypeName } }); - CBO.SetTestableInstance(this._mockCBO.Object); + CBO.SetTestableInstance(this.mockCBO.Object); // create instance of the SearchServiceController var request = new HttpRequestMessage(); @@ -138,7 +143,7 @@ public void SetUp() provider.Setup(x => x.TryFindModuleInfo(request, out expectedModule)).Returns(true); configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - this._searchServiceController = new SearchServiceController(HtmlModDefId) { Request = request }; + this.searchServiceController = new SearchServiceController(HtmlModDefId) { Request = request }; this.CreateNewLuceneControllerInstance(); } @@ -147,7 +152,7 @@ public void SetUp() public void TearDown() { Globals.DependencyProvider = null; - this._luceneController.Dispose(); + this.luceneController.Dispose(); this.DeleteIndexFolder(); CBO.ClearInstance(); TabController.ClearInstance(); @@ -177,12 +182,12 @@ public void GetSearchResultsDetailed() // user doc var userdoc = new SearchDocument { UniqueKey = "key06", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId731 }; - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.AddSearchDocument(doc4); - this._internalSearchController.AddSearchDocument(doc5); - this._internalSearchController.AddSearchDocument(userdoc); + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(doc3); + this.internalSearchController.AddSearchDocument(doc4); + this.internalSearchController.AddSearchDocument(doc5); + this.internalSearchController.AddSearchDocument(userdoc); var query = new SearchQuery { @@ -223,10 +228,10 @@ public void GetSearchResultsBasic() var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; var userdoc = new SearchDocument { UniqueKey = "key03", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(userdoc); - this._internalSearchController.Commit(); + this.internalSearchController.AddSearchDocument(doc1); + this.internalSearchController.AddSearchDocument(doc2); + this.internalSearchController.AddSearchDocument(userdoc); + this.internalSearchController.Commit(); var query = new SearchQuery { @@ -286,8 +291,8 @@ public void ModifyingDocumentsDoesNotCreateDuplicates() NumericKeys = { { "points", 5 } }, }; - this._internalSearchController.AddSearchDocument(originalDocument); - this._internalSearchController.Commit(); + this.internalSearchController.AddSearchDocument(originalDocument); + this.internalSearchController.Commit(); var modifiedDocument = new SearchDocument { @@ -304,8 +309,8 @@ public void ModifyingDocumentsDoesNotCreateDuplicates() NumericKeys = { { "points", 8 }, { "point2", 7 } }, }; - this._internalSearchController.AddSearchDocument(modifiedDocument); - this._internalSearchController.Commit(); + this.internalSearchController.AddSearchDocument(modifiedDocument); + this.internalSearchController.Commit(); var query = new SearchQuery { @@ -334,62 +339,62 @@ public void ModifyingDocumentsDoesNotCreateDuplicates() private void CreateNewLuceneControllerInstance() { - if (this._luceneController != null) + if (this.luceneController != null) { LuceneController.ClearInstance(); - this._luceneController.Dispose(); + this.luceneController.Dispose(); } - this._luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(this._luceneController); + this.luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this.luceneController); } private void SetupUserController() { - this._mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns( + this.mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns( new UserInfo { UserID = UserId1, Username = UserName1, Profile = new UserProfile { } }); - UserController.SetTestableInstance(this._mockUserController.Object); + UserController.SetTestableInstance(this.mockUserController.Object); } private void SetupHostController() { - this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns( + this.mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns( SearchIndexFolder); - this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())). - Returns(this._readerStaleTimeSpan); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns( + this.mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())). + Returns(this.readerStaleTimeSpan); + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns( Constants.DefaultSearchTitleBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns( + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns( Constants.DefaultSearchTagBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns( + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns( Constants.DefaultSearchKeywordBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())). + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())). Returns(Constants.DefaultSearchDescriptionBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns( + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns( Constants.DefaultSearchAuthorBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns( + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns( Constants.DefaultMinLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns( + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns( Constants.DefaultMaxLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns( + this.mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns( DefaultSearchRetryTimes); - HostController.RegisterInstance(this._mockHostController.Object); + HostController.RegisterInstance(this.mockHostController.Object); } private void SetupDataProvider() { // Standard DataProvider Path for Logging - this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + this.mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); - this._mockDataProvider.Setup(d => d.GetSearchModules(It.IsAny())).Returns(this.GetSearchModules); - this._mockDataProvider.Setup(d => d.GetModuleDefinitions()).Returns(this.GetModuleDefinitions); - this._mockDataProvider.Setup(d => d.GetAllSearchTypes()).Returns(this.GetAllSearchTypes); - this._mockDataProvider.Setup(d => d.GetUser(It.IsAny(), It.IsAny())).Returns(this.GetUser); - this._mockDataProvider.Setup(d => d.GetTabs(It.IsAny())).Returns(this.GetTabs); - this._mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(this.GetPortalGroups); + this.mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + this.mockDataProvider.Setup(d => d.GetSearchModules(It.IsAny())).Returns(this.GetSearchModules); + this.mockDataProvider.Setup(d => d.GetModuleDefinitions()).Returns(this.GetModuleDefinitions); + this.mockDataProvider.Setup(d => d.GetAllSearchTypes()).Returns(this.GetAllSearchTypes); + this.mockDataProvider.Setup(d => d.GetUser(It.IsAny(), It.IsAny())).Returns(this.GetUser); + this.mockDataProvider.Setup(d => d.GetTabs(It.IsAny())).Returns(this.GetTabs); + this.mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(this.GetPortalGroups); - DataService.RegisterInstance(this._mockDataService.Object); + DataService.RegisterInstance(this.mockDataService.Object); } private void SetupPortalSettings() @@ -401,16 +406,16 @@ private void SetupPortalSettings() private void SetupModuleController() { - this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId1), It.Is(p => p == PortalId0), false)).Returns( + this.mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId1), It.Is(p => p == PortalId0), false)).Returns( new ModuleInfo { ModuleID = HtmlModuleId1, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle1 }); - this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId2), It.Is(p => p == PortalId0), false)).Returns( + this.mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId2), It.Is(p => p == PortalId0), false)).Returns( new ModuleInfo { ModuleID = HtmlModuleId2, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle2 }); - this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId3), It.Is(p => p == PortalId0), false)).Returns( + this.mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId3), It.Is(p => p == PortalId0), false)).Returns( new ModuleInfo { ModuleID = HtmlModuleId3, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle3 }); - this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId4), It.Is(p => p == PortalId0), false)).Returns( + this.mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId4), It.Is(p => p == PortalId0), false)).Returns( new ModuleInfo { ModuleID = HtmlModuleId4, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle4 }); - ModuleController.SetTestableInstance(this._mockModuleController.Object); + ModuleController.SetTestableInstance(this.mockModuleController.Object); } private void DeleteIndexFolder() @@ -719,7 +724,7 @@ private IEnumerable GetGroupBasicViewResults(SearchQuery query LocalizedName = UserSearchTypeName, ModuleDefinitionId = 0, }; - var results = this._searchServiceController.GetGroupedBasicViews(query, userSearchContentSource, PortalId0); + var results = this.searchServiceController.GetGroupedBasicViews(query, userSearchContentSource, PortalId0); return results; } @@ -727,7 +732,7 @@ private IEnumerable GetGroupedDetailViewResults(SearchQuery s { bool more = false; int totalHits = 0; - var results = this._searchServiceController.GetGroupedDetailViews(searchQuery, UserSearchTypeId, out totalHits, out more); + var results = this.searchServiceController.GetGroupedDetailViews(searchQuery, UserSearchTypeId, out totalHits, out more); return results; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs index 6f0f488cd7c..633e76ac5a1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs @@ -2,158 +2,170 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Web.InternalServices -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Tabs.TabVersions; - using DotNetNuke.Entities.Users; - using DotNetNuke.Tests.Utilities.Mocks; - using Moq; - using NUnit.Framework; - - [TestFixture] - public class TabVersionControllerTests - { - private const int UserID = 1; - private const int TabID = 99; - private readonly DateTime ServerCreateOnDate = new DateTime(2018, 08, 15, 12, 0, 0, DateTimeKind.Unspecified); - - private Mock _mockCBO; - private Mock _mockUserController; - private Mock _mockHostController; - - [SetUp] - public void Setup() - { - MockComponentProvider.ResetContainer(); - this.SetupCBO(); - this.SetupHostController(); - } - - [Test] - [TestCaseSource(typeof(TestCaseFactory), "TestCases")] - public void GetTabVersions_Verify_User_Preferred_TimeZone(string userPreferredTimeZone, DateTime expectedDateTime) - { - // Arrange - this.SetupUserController(userPreferredTimeZone); - - // Act - var tabVersionController = new TabVersionControllerTestable(); - var tabVersions = tabVersionController.GetTabVersions(TabID); - var tabVersion = tabVersions.FirstOrDefault(); - var user = UserController.Instance.GetCurrentUserInfo(); - var userTimeZone = user.Profile.PreferredTimeZone; - - var localizedDate = TimeZoneInfo.ConvertTime(tabVersion.CreatedOnDate, DateUtilsTestable.GetDatabaseDateTimeOffset(), userTimeZone); - - // Assert - Assert.AreEqual(localizedDate, expectedDateTime); - } - - private void SetupCBO() - { - this._mockCBO = new Mock(); - this._mockCBO.Setup(c => c.GetCachedObject>(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(this.GetMockedTabVersions); - CBO.SetTestableInstance(this._mockCBO.Object); - } - - private void SetupUserController(string timeZoneId) - { - this._mockUserController = new Mock(); - this._mockUserController.Setup(userController => userController.GetCurrentUserInfo()).Returns(this.GetMockedUser(timeZoneId)); - UserController.SetTestableInstance(this._mockUserController.Object); - } - - private UserInfo GetMockedUser(string timeZoneId) - { - var profile = new UserProfile() - { - PreferredTimeZone = this.GetMockedUserTimeZone(timeZoneId), - }; - - profile.ProfileProperties.Add(new Entities.Profile.ProfilePropertyDefinition(99) - { - CreatedByUserID = UserID, - PropertyDefinitionId = 20, - PropertyCategory = "Preferences", - PropertyName = "PreferredTimeZone", - PropertyValue = this.GetMockedUserTimeZone(timeZoneId).Id, - }); - var user = new UserInfo() - { - Profile = profile, - UserID = UserID, - PortalID = 99, - }; - - return user; - } - - private TimeZoneInfo GetMockedUserTimeZone(string timeZoneId) - { - return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); - } - - private TabVersion GetMockedTabVersion() - { - var tabVersion = new TabVersion - { - IsPublished = true, - TabId = TabID, - TabVersionId = 1, - Version = 1, - CreatedByUserID = UserID, - }; - tabVersion.GetType().BaseType.GetProperty("CreatedOnDate").SetValue(tabVersion, this.ServerCreateOnDate, null); - - return tabVersion; - } - - private List GetMockedTabVersions() - { - return new List() - { - this.GetMockedTabVersion(), - }; - } - - private void SetupHostController() - { - this._mockHostController = new Mock(); - this._mockHostController.Setup(c => c.GetString(It.IsRegex("PerformanceSetting"))).Returns(Globals.PerformanceSettings.LightCaching.ToString()); - HostController.RegisterInstance(this._mockHostController.Object); - } - - private class TabVersionControllerTestable : TabVersionController - {} - - private class DateUtilsTestable : DateUtils - { - public static new TimeZoneInfo GetDatabaseDateTimeOffset() - { - var timeZoneId = "UTC"; - return TimeZoneInfo.CreateCustomTimeZone(timeZoneId, new TimeSpan(0, 0, 0), timeZoneId, timeZoneId); - } - } - - private class TestCaseFactory - { - public static IEnumerable TestCases() - { - yield return new TestCaseData("Central European Standard Time", new DateTime(2018, 08, 15, 14, 0, 0)); - yield return new TestCaseData("Russian Standard Time", new DateTime(2018, 08, 15, 15, 0, 0)); - yield return new TestCaseData("SE Asia Standard Time", new DateTime(2018, 08, 15, 19, 0, 0)); - } - } - - // Assuming 12:00 Aug 15, 2018 server local time - } -} +namespace DotNetNuke.Tests.Web.InternalServices +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Tests.Utilities.Mocks; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class TabVersionControllerTests + { + private const int UserID = 1; + private const int TabID = 99; + private readonly DateTime ServerCreateOnDate = new DateTime(2018, 08, 15, 12, 0, 0, DateTimeKind.Unspecified); + + private Mock mockCBO; + private Mock mockUserController; + private Mock mockHostController; + + [SetUp] + public void Setup() + { + MockComponentProvider.ResetContainer(); + this.SetupCBO(); + this.SetupHostController(); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => Mock.Of()); + serviceCollection.AddTransient(container => (IHostSettingsService)this.mockHostController.Object); + Globals.DependencyProvider = serviceCollection.BuildServiceProvider(); + } + + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] + public void GetTabVersions_Verify_User_Preferred_TimeZone(string userPreferredTimeZone, DateTime expectedDateTime) + { + // Arrange + this.SetupUserController(userPreferredTimeZone); + + // Act + var tabVersionController = new TabVersionControllerTestable(); + var tabVersions = tabVersionController.GetTabVersions(TabID); + var tabVersion = tabVersions.FirstOrDefault(); + var user = UserController.Instance.GetCurrentUserInfo(); + var userTimeZone = user.Profile.PreferredTimeZone; + + var localizedDate = TimeZoneInfo.ConvertTime(tabVersion.CreatedOnDate, DateUtilsTestable.GetDatabaseDateTimeOffset(), userTimeZone); + + // Assert + Assert.AreEqual(localizedDate, expectedDateTime); + } + + private void SetupCBO() + { + this.mockCBO = new Mock(); + this.mockCBO.Setup(c => c.GetCachedObject>(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(this.GetMockedTabVersions); + CBO.SetTestableInstance(this.mockCBO.Object); + } + + private void SetupUserController(string timeZoneId) + { + this.mockUserController = new Mock(); + this.mockUserController.Setup(userController => userController.GetCurrentUserInfo()).Returns(this.GetMockedUser(timeZoneId)); + UserController.SetTestableInstance(this.mockUserController.Object); + } + + private UserInfo GetMockedUser(string timeZoneId) + { + var profile = new UserProfile() + { + PreferredTimeZone = this.GetMockedUserTimeZone(timeZoneId), + }; + + profile.ProfileProperties.Add(new Entities.Profile.ProfilePropertyDefinition(99) + { + CreatedByUserID = UserID, + PropertyDefinitionId = 20, + PropertyCategory = "Preferences", + PropertyName = "PreferredTimeZone", + PropertyValue = this.GetMockedUserTimeZone(timeZoneId).Id, + }); + var user = new UserInfo() + { + Profile = profile, + UserID = UserID, + PortalID = 99, + }; + + return user; + } + + private TimeZoneInfo GetMockedUserTimeZone(string timeZoneId) + { + return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); + } + + private TabVersion GetMockedTabVersion() + { + var tabVersion = new TabVersion + { + IsPublished = true, + TabId = TabID, + TabVersionId = 1, + Version = 1, + CreatedByUserID = UserID, + }; + tabVersion.GetType().BaseType.GetProperty("CreatedOnDate").SetValue(tabVersion, this.ServerCreateOnDate, null); + + return tabVersion; + } + + private List GetMockedTabVersions() + { + return new List() + { + this.GetMockedTabVersion(), + }; + } + + private void SetupHostController() + { + this.mockHostController = new Mock(); + this.mockHostController.Setup(c => c.GetString(It.IsRegex("PerformanceSetting"))).Returns(Globals.PerformanceSettings.LightCaching.ToString()); + this.mockHostController.As(); + } + + private class TabVersionControllerTestable : TabVersionController + {} + + private class DateUtilsTestable : DateUtils + { + public static new TimeZoneInfo GetDatabaseDateTimeOffset() + { + var timeZoneId = "UTC"; + return TimeZoneInfo.CreateCustomTimeZone(timeZoneId, new TimeSpan(0, 0, 0), timeZoneId, timeZoneId); + } + } + + private class TestCaseFactory + { + public static IEnumerable TestCases() + { + yield return new TestCaseData("Central European Standard Time", new DateTime(2018, 08, 15, 14, 0, 0)); + yield return new TestCaseData("Russian Standard Time", new DateTime(2018, 08, 15, 15, 0, 0)); + yield return new TestCaseData("SE Asia Standard Time", new DateTime(2018, 08, 15, 19, 0, 0)); + } + } + + // Assuming 12:00 Aug 15, 2018 server local time + } +} diff --git a/DNN Platform/Website/ErrorPage.aspx b/DNN Platform/Website/ErrorPage.aspx index 89baf0b5225..bf0e0c9c2ae 100644 --- a/DNN Platform/Website/ErrorPage.aspx +++ b/DNN Platform/Website/ErrorPage.aspx @@ -16,7 +16,7 @@ -

DNN Error

+

Application Error


diff --git a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.nl-NL.resx b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.nl-NL.resx index 7dc45beb330..2a030dcbc17 100644 --- a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.nl-NL.resx +++ b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.nl-NL.resx @@ -184,16 +184,16 @@ Controle van machtiging op mappen en bestanden - &lt;div class="permission"&gt;&lt;img alt=afbeelding geeft de beveiligingsintellingen van de hoofdfolder van de website weer, Dit moet zijn Lezen, Schrijven en Wijzingen voor de ASPNET of NT AUTHORITY/NETWORK SERVICE accounts." src="..\403-3.gif" align="right" hspace="10"/&gt; + &lt;div class="permission"&gt;&lt;img alt=afbeelding geeft de beveiligingsintellingen van de hoofdfolder van de website weer, Dit moet zijn Lezen, Schrijven en Wijzigen voor de ASPNET of NT AUTHORITY/NETWORK SERVICE accounts." src="..\403-3.gif" align="right" hspace="10"/&gt; &lt;p&gt;&lt;b&gt;&lt;font color='red'&gt;De website voldoet niet aan de beveiligingscheck&lt;/font&gt;&lt;/b&gt;&lt;/p&gt; -Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Rechter muis klik op de folder en selecteer delen en beveiliging uit het popup menu. selecteer de beveiligings tab. Voeg de vereiste gebruikers toe en stel de juiste rechten in. +Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Rechtermuisklik op de folder en selecteer Delen en Beveiliging in het popupmenu. Selecteer de beveiligingstab. Voeg de vereiste gebruikers toe en stel de juiste rechten in. &lt;br/&gt;&lt;br/&gt; &lt;h3&gt;Bij gebruik van Windows 2000 - IIS5&lt;/h3&gt; -&lt;p&gt;De ASPNET User Account moet Lees, Schrijf, en wijzing rechten hebben op de hoofdfolder van uw website&lt;/p&gt; +&lt;p&gt;De ASPNET User Account moet Lees, Schrijf, en Wijzigrechten hebben op de hoofdfolder van uw website&lt;/p&gt; &lt;h3&gt;Bij gebruik van Windows 2003, Windows Vista of Windows Server 2008 en IIS6 of IIS7&lt;/h3&gt; -&lt;p&gt;De NT AUTHORITY\NETWORK SERVICE User Account moet lees, Schrijf, en Wijzing rechten hebben op de hoofd folder van uw website.&lt;/p&gt; +&lt;p&gt;De NT AUTHORITY\NETWORK SERVICE User Account moet Lees, Schrijf en Wijzigrechten hebben op de hoofdfolder van uw website.&lt;/p&gt; &lt;h3&gt;Bij gebruik van Windows 7 of Windows Server 2008 R2 en IIS7.5&lt;/h3&gt; -&lt;p&gt;Moet de IIS AppPool\DefaultAppPool User Account Lees, Schrijf, en Wijzig rechten hebben op de hoofd folder van uw website.&lt;/p&gt;&lt;p&gt;&lt;a class="dnnPrimaryAction" href=""&gt;Recheck&lt;/a&gt;&lt;/p&gt;&lt;/div&gt; +&lt;p&gt;Moet de IIS AppPool\DefaultAppPool User Account Lees, Schrijf en Wijzigrechten hebben op de hoofdfolder van uw website.&lt;/p&gt;&lt;p&gt;&lt;a class="dnnPrimaryAction" href=""&gt;Recheck&lt;/a&gt;&lt;/p&gt;&lt;/div&gt; Controleren van machtiging op mappen en bestanden @@ -319,13 +319,13 @@ Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Start installatie - Dit taalpakket is ouder dan de huidige applicatie versie: + Dit taalpakket is ouder dan de huidige applicatieversie: Activeren van de licentie - Er zijn geen installatie errors gelogd + Er zijn geen installatiefouten gelogd Geen installatielog diff --git a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.nl-NL.resx b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.nl-NL.resx index 00308e59305..9d712f854c0 100644 --- a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.nl-NL.resx +++ b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.nl-NL.resx @@ -22,12 +22,12 @@ Accountinformatie - Je staat op het punt om je website te upgraden naar een recentere versie van DNNPlatform. Het toepassen van upgrades op een consistente basis is de beste manier om ervoor te zorgen dat je de integriteit van de website en de veiligheid van de gebruikers garandeert <br /> + Je staat op het punt om je website te upgraden naar een recentere versie van DNNPlatform. Het toepassen van upgrades op een consistente basis is de beste manier om ervoor te zorgen dat je de integriteit van de website en de veiligheid van de gebruikers garandeert. <br /> Voordat je verder gaat met het geautomatiseerde upgrade-proces moet je ervoor zorgen dat: <ul> -<li>je de upgrade eerst test in een testogeving,</li> +<li>je de upgrade eerst test in een testomgeving,</li> <li>je de huidige installatie hebt gedocumenteerd</li> -<li>je modules van derde op compatibilietit hebt gecontroleerd</li> +<li>je modules van derden op compatibiliteit hebt gecontroleerd</li> <li>je een backup hebt gemaakt van de productiesite, zodat je altijd terug kan als er iets mis gaat</li> </ ul> diff --git a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/GridCell/index.jsx b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/GridCell/index.jsx index 06fade2b851..71aaff1ca98 100644 --- a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/GridCell/index.jsx +++ b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/GridCell/index.jsx @@ -4,13 +4,22 @@ import "./style.less"; class GridCell extends Component { getStyle() { - const {props} = this; - return Object.assign({ width: (props.columnSize || 100) + (props.type ? props.type : "%") }, props.style); + const { props } = this; + return Object.assign( + { width: (props.columnSize || 100) + (props.type ? props.type : "%") }, + props.style + ); } render() { - const {props} = this; + const { props } = this; return ( -
+
{ + if (props.onClick) props.onClick(e); + }} + > {props.children}
); @@ -19,14 +28,15 @@ class GridCell extends Component { GridCell.propTypes = { children: PropTypes.node, - columnSize: PropTypes.number, + columnSize: PropTypes.number, type: PropTypes.string, style: PropTypes.object, - className: PropTypes.string + className: PropTypes.string, + onClick: PropTypes.func, }; GridCell.defaultProps = { - className: "" + className: "", }; -export default GridCell; \ No newline at end of file +export default GridCell; diff --git a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/package.json b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/package.json index 27afb7f3abc..8a441d32b40 100644 --- a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/package.json +++ b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/package.json @@ -6,6 +6,7 @@ "start": "npm run webpack", "test": "echo \"Error: no test specified\" && exit 1", "build": "set NODE_ENV=production&&webpack -p", + "debug": "set NODE_ENV=debug&&webpack -p", "watch": "set NODE_ENV=debug & webpack --mode=development --progress --colors --watch", "webpack": "webpack-dev-server -d --port 8050 --hot --inline --content-base dist/ --history-api-fallback" }, diff --git a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/HeaderRow/index.jsx b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/HeaderRow/index.jsx index d1e20a2f605..22f56ca3023 100644 --- a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/HeaderRow/index.jsx +++ b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/HeaderRow/index.jsx @@ -1,27 +1,45 @@ -import PropTypes from 'prop-types'; +import PropTypes from "prop-types"; import React, { Component } from "react"; import { GridCell } from "@dnnsoftware/dnn-react-common"; import "./style.less"; class ExtensionHeader extends Component { - render() { - return ( - - { - this.props.headers.map((header, index) => { - return -
{header.header || "Default"}
-
; - }) - } + render() { + return ( + + {this.props.headers.map((header, index) => { + return ( + { + if (this.props.changeSortOrder && header.isSortable) + this.props.changeSortOrder( + header.columnName, + header.columnName == this.props.currentSortColumn + ? !this.props.currentSortAscending + : true + ); + }} + > +
{header.header || "Default"}
- ); - } + ); + })} +
+ ); + } } ExtensionHeader.propTypes = { - headers: PropTypes.array.isRequired + headers: PropTypes.array.isRequired, + changeSortOrder: PropTypes.func, + currentSortAscending: PropTypes.bool, + currentSortColumn: PropTypes.string, }; - -export default ExtensionHeader; \ No newline at end of file +export default ExtensionHeader; diff --git a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/HeaderRow/style.less b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/HeaderRow/style.less index 57119cee18e..35613d7967b 100644 --- a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/HeaderRow/style.less +++ b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/HeaderRow/style.less @@ -1,13 +1,16 @@ @import "~@dnnsoftware/dnn-react-common/styles/index.less"; .header-row { - padding: 10px 0 10px; - border-bottom: 1px solid @alto; - .dnn-grid-cell { - padding: 0 15px; - } - .dnn-grid-cell.empty{ - text-indent: -100px; - overflow: hidden; - } - text-transform: uppercase; -} \ No newline at end of file + padding: 10px 0 10px; + border-bottom: 1px solid @alto; + .dnn-grid-cell { + padding: 0 15px; + } + .dnn-grid-cell.empty { + text-indent: -100px; + overflow: hidden; + } + text-transform: uppercase; + .sortable { + cursor: pointer; + } +} diff --git a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/index.jsx b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/index.jsx index d34030e3cb5..ade746f8a74 100644 --- a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/index.jsx +++ b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/src/components/UserTable/index.jsx @@ -91,9 +91,9 @@ class UserTable extends Component { headers = [{index: 3, size: columnSizes.find(x=>x.index===3).size, header: ""}]; } headers = headers.concat([ - {index: 5, size: columnSizes.find(x=>x.index===5).size, header: Localization.get("Name.Header")}, - {index: 10, size: columnSizes.find(x=>x.index===10).size, header: Localization.get("Email.Header")}, - {index: 15, size: columnSizes.find(x=>x.index===15).size, header: Localization.get("Created.Header")}, + {index: 5, size: columnSizes.find(x=>x.index===5).size, header: Localization.get("Name.Header"), isSortable: true, columnName: "DisplayName"}, + {index: 10, size: columnSizes.find(x=>x.index===10).size, header: Localization.get("Email.Header"), isSortable: true, columnName: "Email"}, + {index: 15, size: columnSizes.find(x=>x.index===15).size, header: Localization.get("Created.Header"), isSortable: true, columnName: "Joined"}, {index: 25, size: columnSizes.find(x=>x.index===25).size, header:""}]); if (this.props.getUserColumns !== undefined && typeof this.props.getUserColumns ==="function") { let extraColumns = this.props.getUserColumns(); @@ -120,7 +120,7 @@ class UserTable extends Component { const createUserBox = () => []; return ( - + 0 && @@ -111,7 +119,8 @@ class Body extends Component { } - this.userTable = node} appSettings={appSettings} filter={state.searchParameters.filter}/> + this.userTable = node} appSettings={appSettings} filter={state.searchParameters.filter} + changeSortOrder={(c, a) => this.onSortChanged(c, a)} currentSortAscending={state.searchParameters.sortAscending} currentSortColumn={state.searchParameters.sortColumn} /> {
{ - if (_term.TermId === parentTermId) { - parentTerm = _term; - return parentTerm; - } else { - if (findInChildren(_term.ChildTerms, parentTermId)) { - parentTerm = findInChildren(_term.ChildTerms, parentTermId); - return parentTerm; - } - } - }); return parentTerm; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Attributes/RegistrationFieldsAttribute.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Attributes/RegistrationFieldsAttribute.cs index ba71ac36922..63fdc3c18b1 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Attributes/RegistrationFieldsAttribute.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Attributes/RegistrationFieldsAttribute.cs @@ -16,14 +16,16 @@ namespace Dnn.PersonaBar.Security.Attributes [AttributeUsage(AttributeTargets.Property)] class RegistrationFieldsAttribute : ValidationAttribute { - public RegistrationFieldsAttribute(string registrationFormType, string requireUniqueDisplayName) + public RegistrationFieldsAttribute(string registrationFormType, string requireUniqueDisplayName, string displayNameFormat) { this.RegistrationFormTypePropertyName = registrationFormType; - this.RequireUniqueDisplayNamePropertyName = requireUniqueDisplayName; + this.RequireUniqueDisplayNamePropertyName = requireUniqueDisplayName; + this.DisplayNameFormatPropertyName = displayNameFormat; } public string RegistrationFormTypePropertyName { get; private set; } - public string RequireUniqueDisplayNamePropertyName { get; private set; } + public string RequireUniqueDisplayNamePropertyName { get; private set; } + public string DisplayNameFormatPropertyName { get; private set; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { @@ -96,6 +98,22 @@ protected override ValidationResult IsValid(object value, ValidationContext vali { PortalController.UpdatePortalSetting(portalId, "Registration_RegistrationFormType", "0", false); return new ValidationResult(Localization.GetString(Constants.NoDisplayName, Constants.LocalResourcesFile)); + } + + var displayNameFormatValue = string.Empty; + + try + { + displayNameFormatValue = validationContext.ObjectType.GetProperty(this.DisplayNameFormatPropertyName).GetValue(validationContext.ObjectInstance, null).ToString(); + } + catch + { + return new ValidationResult(string.Format(Localization.GetString(Constants.NotValid, Constants.LocalResourcesFile), this.DisplayNameFormatPropertyName, displayNameFormatValue)); + } + + if (!registrationFields.Contains("DisplayName") && string.IsNullOrWhiteSpace(displayNameFormatValue)) + { + return new ValidationResult(Localization.GetString(Constants.IncorrectDisplayNameConfiguration, Constants.LocalResourcesFile)); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Constants.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Constants.cs index 54df7fbc44a..fd10b9ba99e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Constants.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Constants.cs @@ -22,7 +22,8 @@ public static class Constants public const string NoEmail = "NoEmail"; public const string ContainsDuplicateAddresses = "ContainsDuplicateAddresses"; public const string DeletedTab = "DeletedTab"; - public const string DisabledTab = "DisabledTab"; + public const string DisabledTab = "DisabledTab"; + public const string IncorrectDisplayNameConfiguration = "IncorrectDisplayNameConfiguration"; public const string LocalResourcesFile = "~/DesktopModules/admin/Dnn.PersonaBar/Modules/Dnn.Security/App_LocalResources/Security.resx"; } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Services/DTO/UpdateRegistrationSettingsRequest.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Services/DTO/UpdateRegistrationSettingsRequest.cs index fd967102273..f117288955d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Services/DTO/UpdateRegistrationSettingsRequest.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Services/DTO/UpdateRegistrationSettingsRequest.cs @@ -20,7 +20,7 @@ public class UpdateRegistrationSettingsRequest [RegistrationFormTypeOption] public int RegistrationFormType { get; set; } - [RegistrationFields("RegistrationFormType", "RequireUniqueDisplayName")] + [RegistrationFields("RegistrationFormType", "RequireUniqueDisplayName", "DisplayNameFormat")] public string RegistrationFields { get; set; } public bool RequireUniqueDisplayName { get; set; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/admin/personaBar/Dnn.Security/App_LocalResources/Security.resx b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/admin/personaBar/Dnn.Security/App_LocalResources/Security.resx index b19db47aad6..9cd34567b9b 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/admin/personaBar/Dnn.Security/App_LocalResources/Security.resx +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/admin/personaBar/Dnn.Security/App_LocalResources/Security.resx @@ -667,7 +667,7 @@ Allowable File Extensions: - Settings has been updated. + Settings have been updated. Could not update settings. Please try later. @@ -1147,4 +1147,7 @@ Redirection has been moved to Site Settings + + The Display Name configuration is not correct. Either provide Display Name Format or include Display Name in the list of fields. + \ No newline at end of file diff --git a/gitversion.yml b/gitversion.yml index 9da2681ae3e..bf289bdaf60 100644 --- a/gitversion.yml +++ b/gitversion.yml @@ -2,8 +2,9 @@ next-version: 9.6.0 commit-date-format: 'yyyyMMdd' assembly-file-versioning-format: '{Major}.{Minor}.{Patch}.{CommitsSinceVersionSource}' mode: ContinuousDeployment +ignore: + commits-before: 2020-01-01T00:00:00 branches: - future: regex: future?[/-] tag: 'alpha'