public void Validate_ItemNameQueryIsValid_Passes() { // Arrange var criteriaValidator = new CriteriaValidator(); var searchOption = SearchOption.ItemName; var searchCriteria = new ItemNameSearchCriteria { Query = "1", ProjectIds = new[] { 1 } }; Exception exception = null; // Act try { criteriaValidator.Validate(searchOption, true, searchCriteria, 1); } catch (Exception ex) { exception = ex; } // Assert Assert.IsNull(exception, "Exception should not have been thrown"); }
public async Task SearchName_RepoThrowsException_LogShouldBeCalled() { // Arrange var searchCriteria = new ItemNameSearchCriteria { Query = "Test", ProjectIds = new List <int> { 5 } }; var startOffset = 0; var pageSize = 200; var logMock = new Mock <IServiceLogRepository>(MockBehavior.Strict); logMock.Setup(t => t.LogError(It.IsAny <string>(), It.IsAny <Exception>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>())).Returns(Task.Delay(1)); var exceptionToBeThrown = new Exception("MyException"); var controller = CreateControllerForExceptionCases(logMock, exceptionToBeThrown); Exception actualException = null; // Act try { var result = await controller.SearchName(searchCriteria, startOffset, pageSize); } catch (Exception ex) { actualException = ex; } // Assert Assert.IsNotNull(actualException); Assert.AreEqual(exceptionToBeThrown.Message, actualException.Message, "Incorrect exception was thrown"); logMock.Verify(t => t.LogError(It.IsAny <string>(), It.IsAny <Exception>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()), Times.Exactly(1)); }
public void Validate_ItemNameQueryNoProjectProvided_ThrowsBadRequestException() { // Arrange var criteriaValidator = new CriteriaValidator(); var searchOption = SearchOption.ItemName; var searchCriteria = new ItemNameSearchCriteria { Query = "12345", ProjectIds = new int[] { } }; BadRequestException badRequestException = null; // Act try { criteriaValidator.Validate(searchOption, true, searchCriteria, 1); } catch (BadRequestException bre) { badRequestException = bre; } // Assert Assert.IsNotNull(badRequestException, "Bad request exception should have been thrown"); Assert.IsTrue(badRequestException.ErrorCode == ErrorCodes.IncorrectSearchCriteria); }
private static IItemSearchRepository CreateItemNameRepository <T>( ItemNameSearchCriteria searchCriteria, ICollection <T> queryResult, IArtifactPermissionsRepository artifactPermissionsRepository, IArtifactRepository artifactRepository) { var connectionWrapper = new SqlConnectionWrapperMock(); var parameters = new Dictionary <string, object> { { "userId", UserId }, { "query", searchCriteria.Query }, { "projectIds", SqlConnectionWrapper.ToDataTable(searchCriteria.ProjectIds) }, { "maxSearchableValueStringSize", MaxSearchableValueStringSize }, { "startOffset", StartOffset }, { "pageSize", PageSize }, { "excludedPredefineds", SqlConnectionWrapper.ToDataTable(SqlItemSearchRepository.GetExcludedPredefineds(searchCriteria)) } }; if (searchCriteria.PredefinedTypeIds != null) { parameters.Add("predefinedTypeIds", SqlConnectionWrapper.ToDataTable(searchCriteria.PredefinedTypeIds)); } connectionWrapper.SetupQueryAsync( "SearchItemNameByItemTypes", parameters, queryResult); var configuration = new Mock <ISearchConfiguration>(); configuration.Setup(c => c.MaxItems).Returns(MaxItems.ToStringInvariant()); configuration.Setup(c => c.MaxSearchableValueStringSize).Returns(MaxSearchableValueStringSize.ToStringInvariant()); return(new SqlItemSearchRepository(connectionWrapper.Object, configuration.Object, artifactPermissionsRepository, artifactRepository)); }
public void ExcludedPredefineds_DoNotShowArtifacts_CorrectResult() { // Arrange var searchCriteria = new ItemNameSearchCriteria { ShowArtifacts = false, ShowBaselinesAndReviews = true, ShowCollections = true }; ItemTypePredefined[] expected = { ItemTypePredefined.Glossary, ItemTypePredefined.TextualRequirement, ItemTypePredefined.PrimitiveFolder, ItemTypePredefined.BusinessProcess, ItemTypePredefined.Actor, ItemTypePredefined.UseCase, ItemTypePredefined.DataElement, ItemTypePredefined.UIMockup, ItemTypePredefined.GenericDiagram, ItemTypePredefined.Document, ItemTypePredefined.Storyboard, ItemTypePredefined.DomainDiagram, ItemTypePredefined.UseCaseDiagram, ItemTypePredefined.Process }; // Act var excludedPredefineds = SqlItemSearchRepository.GetExcludedPredefineds(searchCriteria); // Assert CollectionAssert.AreEquivalent(expected, excludedPredefineds.Cast <ItemTypePredefined>().ToList()); }
public async Task SearchName_WithoutItemTypes_ReturnsResults() { // Arrange var searchCriteria = new ItemNameSearchCriteria { Query = "test", ProjectIds = new[] { 1 } }; ItemNameSearchResult[] queryResult = { new ItemNameSearchResult() }; var permissionsDictionary = new Dictionary <int, RolePermissions> { { 0, RolePermissions.Read } }; var mockArtifactPermissionsRepository = new Mock <IArtifactPermissionsRepository>(); mockArtifactPermissionsRepository.Setup(r => r.GetArtifactPermissions(new List <int> { 0 }, UserId, false, int.MaxValue, true, null)).ReturnsAsync(permissionsDictionary); var itemSearchRepository = CreateItemNameRepository(searchCriteria, queryResult, mockArtifactPermissionsRepository.Object, null); // Act var result = await itemSearchRepository.SearchName(UserId, searchCriteria, StartOffset, PageSize); // Assert CollectionAssert.AreEqual(queryResult, result.Items.ToList()); Assert.AreEqual(queryResult.Length, result.PageItemCount); }
private void ValidateItemNameCriteria(bool modelStateIsValid, ItemNameSearchCriteria searchCriteria, int minSearchQueryLimit = 1) { if (IsCriteriaQueryInvalid(modelStateIsValid, searchCriteria, minSearchQueryLimit) || !searchCriteria.ProjectIds.Any()) { throw new BadRequestException("Please provide correct search criteria", ErrorCodes.IncorrectSearchCriteria); } }
public async Task SearchName_IncludeArtifactPath_ReturnsResults() { // Arrange var searchCriteria = new ItemNameSearchCriteria { Query = "test", ProjectIds = new[] { 1 }, IncludeArtifactPath = true }; ItemNameSearchResult[] queryResult = { new ItemNameSearchResult() }; var permissionsDictionary = new Dictionary <int, RolePermissions> { { 0, RolePermissions.Read } }; var mockArtifactPermissionsRepository = new Mock <IArtifactPermissionsRepository>(); mockArtifactPermissionsRepository.Setup(r => r.GetArtifactPermissions(new List <int> { 0 }, UserId, false, int.MaxValue, true, null)).ReturnsAsync(permissionsDictionary); var artifactInfo = new Artifact() { Id = 1, Name = "ArtifactPath" }; var infoCollection = new List <Artifact> { artifactInfo }; var navigationPaths = new Dictionary <int, IEnumerable <Artifact> > { { 0, infoCollection } }; var mockSqlArtifactRepository = new Mock <IArtifactRepository>(); mockSqlArtifactRepository.Setup(r => r.GetArtifactsNavigationPathsAsync(1, new List <int> { 0 }, false, null, true)).ReturnsAsync(navigationPaths); var itemSearchRepository = CreateItemNameRepository(searchCriteria, queryResult, mockArtifactPermissionsRepository.Object, mockSqlArtifactRepository.Object); // Act var result = await itemSearchRepository.SearchName(UserId, searchCriteria, StartOffset, PageSize); // Assert CollectionAssert.AreEqual(queryResult, result.Items.ToList()); Assert.AreEqual(queryResult.Length, result.PageItemCount); Assert.AreEqual(result.Items.First().ArtifactPath.Count(), 1); Assert.AreEqual(result.Items.First().ArtifactPath.First(), "ArtifactPath"); }
public async Task SearchName_ResultCountMoreThanMax_Success() { // Arrange var searchCriteria = new ItemNameSearchCriteria { Query = "Test", ProjectIds = new List <int> { 5 } }; var startOffset = 0; var pageSize = 200; var controller = CreateController(); // Act var result = await controller.SearchName(searchCriteria, startOffset, pageSize); // Assert Assert.IsNotNull(result); }
internal static IEnumerable <int> GetExcludedPredefineds(ItemNameSearchCriteria searchCriteria) { return(((ItemTypePredefined[])Enum.GetValues(typeof(ItemTypePredefined))).Where(p => { if (p.IsRegularArtifactType()) { return !searchCriteria.ShowArtifacts; } if (p.IsBaselinesAndReviewsGroupType() && p != ItemTypePredefined.BaselineArtifactGroup) { return !searchCriteria.ShowBaselinesAndReviews; } if (p.IsCollectionsGroupType() && p != ItemTypePredefined.CollectionArtifactGroup) { return !searchCriteria.ShowCollections; } return false; }).Cast <int>()); }
public void ExcludedPredefineds_DoNotShowCollections_CorrectResult() { // Arrange ItemTypePredefined[] expected = { ItemTypePredefined.CollectionFolder, ItemTypePredefined.ArtifactCollection }; var searchCriteria = new ItemNameSearchCriteria { ShowArtifacts = true, ShowBaselinesAndReviews = true, ShowCollections = false }; // Act var excludedPredefineds = SqlItemSearchRepository.GetExcludedPredefineds(searchCriteria); // Assert CollectionAssert.AreEquivalent(expected, excludedPredefineds.Cast <ItemTypePredefined>().ToList()); }
public async Task SearchName_WithPredefinedTypeIdsWithSqlException_SqlExceptionOccurs() { // Arrange var searchCriteria = new ItemNameSearchCriteria { Query = "test", ProjectIds = new[] { 1 }, PredefinedTypeIds = new[] { 4104 } }; var permissionsDictionary = new Dictionary <int, RolePermissions> { { 0, RolePermissions.Read } }; var mockArtifactPermissionsRepository = new Mock <IArtifactPermissionsRepository>(); mockArtifactPermissionsRepository.Setup(r => r.GetArtifactPermissions(new List <int> { 0 }, UserId, false, int.MaxValue, true, null)).ReturnsAsync(permissionsDictionary); Exception sqlException = SqlExceptionCreator.NewSqlException(-4); var itemSearchRepository = CreateItemNameRepositoryWithExceptionExpectation <ItemNameSearchResult>(mockArtifactPermissionsRepository.Object, null, sqlException); SqlException actualSqlException = null; // Act try { await itemSearchRepository.SearchName(UserId, searchCriteria, StartOffset, PageSize); } catch (SqlException exception) { actualSqlException = exception; } // Assert Assert.IsNotNull(actualSqlException, "sqlException != null"); Assert.IsTrue(actualSqlException.Number == -4, "Timeout exception should occur"); }
public async Task SearchName_Forbidden() { // Arrange var searchCriteria = new ItemNameSearchCriteria { Query = "Test", ProjectIds = new List <int> { 5 } }; var startOffset = 0; var pageSize = 20; var controller = CreateController(); // Act try { await controller.SearchName(searchCriteria, startOffset, pageSize); } catch (AuthenticationException e) { // Assert Assert.AreEqual(ErrorCodes.UnauthorizedAccess, e.ErrorCode); } }
public async Task <ItemNameSearchResultSet> SearchName( [FromBody] ItemNameSearchCriteria searchCriteria, int?startOffset = null, int?pageSize = null) { // get the UserId from the session var userId = ValidateAndExtractUserId(); _criteriaValidator.Validate(SearchOption.ItemName, ModelState.IsValid, searchCriteria, 1); int searchPageSize = GetPageSize(_searchConfigurationProvider, pageSize, MaxResultCount); int searchStartOffset = GetStartCounter(startOffset, 0, 0); try { var results = await _itemSearchRepository.SearchName(userId, searchCriteria, searchStartOffset, searchPageSize); foreach (var searchItem in results.Items) { searchItem.LockedByUser = searchItem.LockedByUserId.HasValue ? new UserGroup { Id = searchItem.LockedByUserId } : null; } return(results); } catch (Exception ex) { await Log.LogError(LogSource, ex); throw; } }
public async Task SearchName_QueryIsEmpty_BadRequest() { // Arrange var searchCriteria = new ItemNameSearchCriteria { Query = "" }; var controller = CreateController(); // Act BadRequestException badRequestException = null; try { await controller.SearchName(searchCriteria); } catch (BadRequestException e) { badRequestException = e; } // Assert Assert.IsNotNull(badRequestException, "Bad Request Exception should have been thrown"); Assert.AreEqual(ErrorCodes.IncorrectSearchCriteria, badRequestException.ErrorCode, "IncorrectSearchCriteria should be provided as Error code"); }
/// <summary> /// Perform an Item search by SearchName /// </summary> /// <param name="userId"></param> /// <param name="searchCriteria">SearchCriteria object</param> /// <param name="startOffset">Search start offset</param> /// <param name="pageSize">Page Size</param> /// <returns></returns> public async Task <ItemNameSearchResultSet> SearchName( int userId, ItemNameSearchCriteria searchCriteria, int startOffset, int pageSize) { var param = new DynamicParameters(); param.Add("@userId", userId); param.Add("@query", searchCriteria.Query); param.Add("@projectIds", SqlConnectionWrapper.ToDataTable(searchCriteria.ProjectIds)); if (searchCriteria.PredefinedTypeIds != null && searchCriteria.PredefinedTypeIds.Any()) { param.Add("@predefinedTypeIds", SqlConnectionWrapper.ToDataTable(searchCriteria.PredefinedTypeIds)); } if (searchCriteria.ItemTypeIds != null && searchCriteria.ItemTypeIds.Any()) { param.Add("@itemTypeIds", SqlConnectionWrapper.ToDataTable(searchCriteria.ItemTypeIds)); } param.Add("@excludedPredefineds", SqlConnectionWrapper.ToDataTable(GetExcludedPredefineds(searchCriteria))); param.Add("@startOffset", startOffset); param.Add("@pageSize", pageSize); param.Add("@maxSearchableValueStringSize", _searchConfigurationProvider.MaxSearchableValueStringSize); List <ItemNameSearchResult> items; try { items = (await _connectionWrapper.QueryAsync <ItemNameSearchResult>("SearchItemNameByItemTypes", param, commandType: CommandType.StoredProcedure, commandTimeout: _searchConfigurationProvider.SearchTimeout)).ToList(); } catch (SqlException sqlException) { switch (sqlException.Number) { // Sql timeout error case ErrorCodes.SqlTimeoutNumber: throw new SqlTimeoutException("Server did not respond with a response in the allocated time. Please try again later.", ErrorCodes.Timeout); } throw; } var itemIds = items.Select(i => i.ItemId).ToList(); var itemIdsPermissions = // Always getting permissions for the Head version of an artifact. await _artifactPermissionsRepository.GetArtifactPermissions(itemIds, userId); IDictionary <int, IEnumerable <Artifact> > itemsNavigationPaths; if (searchCriteria.IncludeArtifactPath) { itemsNavigationPaths = await _artifactRepository.GetArtifactsNavigationPathsAsync(userId, itemIds, false); } else { itemsNavigationPaths = new Dictionary <int, IEnumerable <Artifact> >(); } // items without permission should be removed items.RemoveAll(item => !itemIdsPermissions.ContainsKey(item.ItemId) || !itemIdsPermissions[item.ItemId].HasFlag(RolePermissions.Read)); var joinedResult = from item in items join permission in itemIdsPermissions.AsEnumerable() on item.ItemId equals permission.Key join path in itemsNavigationPaths on item.Id equals path.Key into paths from lpath in paths.DefaultIfEmpty() select new { item, permission, lpath }; foreach (var result in joinedResult) { result.item.Permissions = result.permission.Value; if (searchCriteria.IncludeArtifactPath) { result.item.ArtifactPath = result.lpath.Value.Select(a => a.Name).ToList(); result.item.IdPath = result.lpath.Value.Select(a => a.Id).ToList(); result.item.ParentPredefinedType = result.lpath.Value.Select(a => a.PredefinedType).FirstOrDefault(); } } return(new ItemNameSearchResultSet { Items = items, PageItemCount = items.Count }); }