internal UnitTestResult RunUnitTest (UnitTest test, string suiteName, string pathName, string testName, TestContext testContext) { var runnerExe = GetCustomConsoleRunnerCommand (); if (runnerExe != null) return RunWithConsoleRunner (runnerExe, test, suiteName, pathName, testName, testContext); ExternalTestRunner runner = (ExternalTestRunner)Runtime.ProcessService.CreateExternalProcessObject (typeof(ExternalTestRunner), testContext.ExecutionContext, UserAssemblyPaths); LocalTestMonitor localMonitor = new LocalTestMonitor (testContext, test, suiteName, testName != null); ITestFilter filter = null; if (test != null) { if (test is UnitTestGroup) { var categoryOptions = (NUnitCategoryOptions) test.GetOptions (typeof(NUnitCategoryOptions)); if (categoryOptions.EnableFilter && categoryOptions.Categories.Count > 0) { string[] cats = new string [categoryOptions.Categories.Count]; categoryOptions.Categories.CopyTo (cats, 0); filter = new CategoryFilter (cats); if (categoryOptions.Exclude) filter = new NotFilter (filter); } else { filter = new TestNameFilter (CollectTests ((UnitTestGroup)test)); } } else { filter = new TestNameFilter (test.TestId); } } RunData rd = new RunData (); rd.Runner = runner; rd.Test = this; rd.LocalMonitor = localMonitor; testContext.Monitor.CancelRequested += new TestHandler (rd.Cancel); UnitTestResult result; var crashLogFile = Path.GetTempFileName (); try { if (string.IsNullOrEmpty (AssemblyPath)) { string msg = GettextCatalog.GetString ("Could not get a valid path to the assembly. There may be a conflict in the project configurations."); throw new Exception (msg); } System.Runtime.Remoting.RemotingServices.Marshal (localMonitor, null, typeof (IRemoteEventListener)); string testRunnerAssembly, testRunnerType; GetCustomTestRunner (out testRunnerAssembly, out testRunnerType); result = runner.Run (localMonitor, filter, AssemblyPath, "", new List<string> (SupportAssemblies), testRunnerType, testRunnerAssembly, crashLogFile); if (testName != null) result = localMonitor.SingleTestResult; ReportCrash (testContext, crashLogFile); } catch (Exception ex) { if (ReportCrash (testContext, crashLogFile)) { result = UnitTestResult.CreateFailure (GettextCatalog.GetString ("Unhandled exception"), null); } else if (!localMonitor.Canceled) { LoggingService.LogError (ex.ToString ()); if (localMonitor.RunningTest != null) { RuntimeErrorCleanup (testContext, localMonitor.RunningTest, ex); } else { testContext.Monitor.ReportRuntimeError (null, ex); throw; } result = UnitTestResult.CreateFailure (ex); } else { result = UnitTestResult.CreateFailure (GettextCatalog.GetString ("Canceled"), null); } } finally { File.Delete (crashLogFile); testContext.Monitor.CancelRequested -= new TestHandler (rd.Cancel); runner.Dispose (); System.Runtime.Remoting.RemotingServices.Disconnect (localMonitor); } return result; }
internal UnitTestResult RunUnitTest (UnitTest test, string suiteName, string testName, TestContext testContext) { ExternalTestRunner runner = (ExternalTestRunner) Runtime.ProcessService.CreateExternalProcessObject (typeof(ExternalTestRunner), testContext.ExecutionContext); LocalTestMonitor localMonitor = new LocalTestMonitor (testContext, runner, test, suiteName, testName != null); ITestFilter filter = null; if (testName != null) { filter = new TestNameFilter (suiteName + "." + testName); } else { NUnitCategoryOptions categoryOptions = (NUnitCategoryOptions) test.GetOptions (typeof(NUnitCategoryOptions)); if (categoryOptions.EnableFilter && categoryOptions.Categories.Count > 0) { string[] cats = new string [categoryOptions.Categories.Count]; categoryOptions.Categories.CopyTo (cats, 0); filter = new CategoryFilter (cats); if (categoryOptions.Exclude) filter = new NotFilter (filter); } } RunData rd = new RunData (); rd.Runner = runner; rd.Test = this; rd.LocalMonitor = localMonitor; testContext.Monitor.CancelRequested += new TestHandler (rd.Cancel); UnitTestResult result; try { if (string.IsNullOrEmpty (AssemblyPath)) { string msg = GettextCatalog.GetString ("Could not get a valid path to the assembly. There may be a conflict in the project configurations."); throw new Exception (msg); } System.Runtime.Remoting.RemotingServices.Marshal (localMonitor, null, typeof (IRemoteEventListener)); result = runner.Run (localMonitor, filter, AssemblyPath, suiteName, new List<string> (SupportAssemblies)); if (testName != null) result = localMonitor.SingleTestResult; } catch (Exception ex) { if (!localMonitor.Canceled) { LoggingService.LogError (ex.ToString ()); if (localMonitor.RunningTest != null) { RuntimeErrorCleanup (testContext, localMonitor.RunningTest, ex); } else { testContext.Monitor.ReportRuntimeError (null, ex); throw ex; } result = UnitTestResult.CreateFailure (ex); } else { result = UnitTestResult.CreateFailure (GettextCatalog.GetString ("Canceled"), null); } } finally { testContext.Monitor.CancelRequested -= new TestHandler (rd.Cancel); runner.Dispose (); System.Runtime.Remoting.RemotingServices.Disconnect (localMonitor); } return result; }
public void CanRetrieveLogFiltersByType() { ICollection <ILogFilter> filters = new List <ILogFilter>(); ICollection <string> categories = new List <string>(); categories.Add("cat1"); categories.Add("cat2"); categories.Add("cat3"); categories.Add("cat4"); filters.Add(new CategoryFilter("category", categories, CategoryFilterMode.AllowAllExceptDenied)); filters.Add(new PriorityFilter("priority", 100)); filters.Add(new LogEnabledFilter("enable", true)); LogFilterHelper helper = new LogFilterHelper(filters, new MockLogFilterErrorHandler(true)); CategoryFilter categoryFilter = helper.GetFilter <CategoryFilter>(); PriorityFilter priorityFilter = helper.GetFilter <PriorityFilter>(); LogEnabledFilter enabledFilter = helper.GetFilter <LogEnabledFilter>(); Assert.IsNotNull(categoryFilter); Assert.AreEqual(4, categoryFilter.CategoryFilters.Count); Assert.IsNotNull(priorityFilter); Assert.AreEqual(100, priorityFilter.MinimumPriority); Assert.IsNotNull(enabledFilter); Assert.IsTrue(enabledFilter.Enabled); }
private async Task SetCategories() { try { CategoryFilter filter = new CategoryFilter() { ForVideos = true, SortType = SortType.Random, Visible = true }; filter.Pagination.RecordsPerPage = 100000000; var response = await new MahwousRepositories().CategoriesRepository.GetFiltered(filter); if (response.Response != null && response.Response.Count > 0) { TabsAdapter adapter = new TabsAdapter(SupportFragmentManager, response.Response.ToList()); ViewPager pager = FindViewById <ViewPager>(Resource.Id.viewPager); pager.Adapter = adapter; TabLayout tabLayout = FindViewById <TabLayout>(Resource.Id.tabLayout); tabLayout.SetupWithViewPager(pager); } else { await SetCategories(); } } catch { await SetCategories(); } }
/// <summary> /// PickObject Element Multiply Categories /// Show Information Element /// </summary> /// <param name="commandData"></param> /// <param name="message"></param> /// <param name="elements"></param> /// <returns></returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { #region Init UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; #endregion try { CategoryFilter categoryFilter = new CategoryFilter { catname = "Walls" }; IList <Reference> references = uidoc.Selection.PickObjects(ObjectType.Element, categoryFilter, "Select Element Filter By Categories "); StringBuilder sb = new StringBuilder(); foreach (Reference r in references) { Autodesk.Revit.DB.Element e = doc.GetElement(r); sb.AppendLine($"{e.Name}-{e.Id}"); } MessageBox.Show($"{sb}"); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) {} catch (Exception e) { MessageBox.Show(e.ToString()); } return(Result.Succeeded); }
public async Task <List <CategoryDto> > GetAllAndSub(CategoryFilter categoryFilter) { var query = _unitOfWork.CategoryRepository.FindAll(); if (categoryFilter.TenantId.HasValue) { query = query.Where(p => p.TenantId == categoryFilter.TenantId.Value); } var categoryOrigins = await query.AsNoTracking().OrderBy(p => p.Name).ToListAsync(); var categoryFilters = categoryOrigins.Where(r => !r.ParentCategoryId.HasValue).OrderBy(r => r.Name).ToList(); if (categoryFilter.Id.HasValue) { var exceptCategory = categoryOrigins.FirstOrDefault(p => p.Id == categoryFilter.Id); categoryFilters = categoryFilters.Where(p => exceptCategory.ParentCategoryId.HasValue || p.Id != exceptCategory.Id) .ToList(); categoryOrigins = categoryOrigins.Where(p => !exceptCategory.ParentCategoryId.HasValue || (p.ParentCategoryId.HasValue && p.ParentCategoryId != exceptCategory.ParentCategoryId)) .ToList(); } var data = GetCategoriesByParent(categoryOrigins, categoryFilters); return(data); }
public IEnumerable <v_Category> ListAllPaging(CategoryFilter filter, int page, int pageSize) { IQueryable <v_Category> model = db.v_Category; if (!string.IsNullOrEmpty(filter.SearchString)) { string searchString = filter.SearchString.Trim(); model = model.Where(x => x.Name.Contains(searchString)); } if (filter.CatalogueId > 0) { model = model.Where(w => w.CatalogueId == filter.CatalogueId); } if (filter.ParentID > 0) { model = model.Where(w => w.ParentID == filter.ParentID); } if (filter.Status.Count() > 0) { model = model.Where(w => filter.Status.Contains(w.Status)); } return(model.OrderByDescending(x => x.CreatedDate).ToPagedList(page, pageSize)); }
public void EntryIsOnlyWrittenToDatabaseWhenPassesCategoryFilter() { LoggingConfiguration loggingConfiguration = BuildProgrammaticConfigForTrace(); this.UpdateConfigForDatabaseTL(loggingConfiguration); // Category Filters ICollection <string> categories = new List <string>(); categories.Add("BlockedByFilter"); var categoryFilter = new CategoryFilter("Category Filter", categories, CategoryFilterMode.DenyAllExceptAllowed); loggingConfiguration.Filters.Add(categoryFilter); this.writer = new LogWriter(loggingConfiguration); this.writer.Write("Test Logging CategoryFilter 1", "General", 1); this.writer.Write("Test Logging CategoryFilter 2", "BlockedByFilter", 2); string dateTimeLogged = DateTime.Now.ToLocalTime().ToString(); int checkCategory1 = this.CheckEntryInDatabase("Test Logging CategoryFilter 1"); Assert.AreEqual(0, checkCategory1); string strMessage = this.CheckEntryInDatabase(); Assert.IsTrue(strMessage.Contains("Timestamp: " + dateTimeLogged + "\r\nMessage: Test Logging CategoryFilter 2\r\nCategory: BlockedByFilter\r\nPriority: 2\r\nEventId: 1")); }
public ActionResult ColorFilter() { CategoryFilter colorFilter = new CategoryFilter(); var colors = db.Colors.ToList(); return(PartialView(colors)); }
public void With_composite_AND_filter_no_result() { PluginBase plugin = new Plugin(); ((Plugin)plugin).AddMinutes(100); ((Plugin)plugin).SetCategory(Guid.NewGuid().ToString()); ((Plugin)plugin).SetLevel(Guid.NewGuid().ToString()); IFilterExpression filter1 = new TimeFilter() { Operator = "<=", Operand = "15" }; IFilterExpression filter2 = new CategoryFilter() { Operator = "in", Operand = "group" }; IFilterExpression filter3 = new LevelFilter() { Operator = "in", Operand = "debug" }; IFilterComposite filter = new AndFilterComposite(); filter.Add(filter1, filter2, filter3); var days = plugin.GetDays(); foreach (var day in days) { var logs = plugin.GetLogs(day); logs = filter.Filter(logs); Assert.True(logs.Count() == 0); } }
public int CreateCategory(CategoryFilter CFilt) { int result = 0; try { SqlCommand sqlCommand = ProjectConnection.CreateCommand(); sqlCommand.CommandText = CREATE_Category_SP; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add(new SqlParameter(IMAGE_USERID_PARAM, SqlDbType.Int)).Value = CFilt.Category.CategoryID; sqlCommand.Parameters.Add(new SqlParameter(IMAGE_CATEGORYID_PARAM, SqlDbType.Int)).Value = CFilt.Category.CategoryDescription; ProjectConnection.Open(); result = sqlCommand.ExecuteNonQuery(); ProjectConnection.Close(); } catch (Exception ex) { throw new Exception("CATEGORY", ex); } finally { if (ProjectConnection.State == ConnectionState.Open) { ProjectConnection.Close(); } } return(result); }
public async Task <int> Count(CategoryFilter filter) { IQueryable <CategoryDAO> CategoryDAOs = DataContext.Category; CategoryDAOs = DynamicFilter(CategoryDAOs, filter); return(await CategoryDAOs.CountAsync()); }
private void UpdateCategory(Category cat, CategoryFilter filter, int index) { bool isOn = filter.IsSet(index); int bIndex = index; var newToggle = Instantiate(classTogglePrefab, transform, false); newToggle.isOn = isOn; newToggle.onValueChanged.AddListener(delegate { OnToggleChange(newToggle, bIndex); }); newToggle.graphic.color = cat.color; var label = newToggle.GetComponentInChildren <Text>(); if (string.IsNullOrEmpty(cat.name)) { label.text = "N/A"; } else { label.text = cat.name; } AddHoverEvent(newToggle.transform.GetChild(0).gameObject, index); toggles.Add(newToggle); }
public async Task <List <CategoryDto> > GetAll(CategoryFilter categoryFilter) { var query = _unitOfWork.CategoryRepository.FindAll(); if (categoryFilter.TenantId.HasValue) { query = query.Where(p => p.TenantId == categoryFilter.TenantId.Value); } if (categoryFilter.Id.HasValue) { query = query.Where(p => p.Id == categoryFilter.Id.Value); } if (!string.IsNullOrEmpty(categoryFilter.Name)) { query = query.Where(p => p.Name.ToLower() == categoryFilter.Name.ToLower()); } var data = await query.Include(p => p.ParentCategory) .AsNoTracking() .OrderBy(p => p.Name).ToListAsync(); return(data.Select(p => new CategoryDto { Id = p.Id, Name = p.Name, ParentCategoryId = p.ParentCategoryId, ParentCategoryName = p.ParentCategory?.Name, Note = p.Note }).ToList()); }
public static CategoryFilter GetDefault() { var filter = new CategoryFilter(); filter.ResetToDefault(); return(filter); }
public ActionResult SizeFilter() { CategoryFilter sizeFilter = new CategoryFilter(); var sizes = db.Sizes.AsEnumerable().Reverse().ToList(); return(PartialView(sizes)); }
public void CopyFrom(CategoryFilter other) { for (int i = 0; i < ArraySize; ++i) { bits[i] = other.bits[i]; } }
public ActionResult ActivityFilter() { CategoryFilter activityFilter = new CategoryFilter(); var activities = db.Activities.Where(a => a.EndDate >= DateTime.Now).ToList(); return(PartialView(activities)); }
void ChainCategoryFilter(IEnumerable <string> categories, bool negate, ref ITestFilter chain) { bool gotCategories = false; if (categories != null) { var filter = new CategoryFilter(); foreach (string c in categories) { Log.Info(LogTag, $" {c}"); filter.AddCategory(c); gotCategories = true; } if (gotCategories) { chain = new AndFilter(chain, negate ? new NotFilter(filter) : (ITestFilter)filter); } } if (!gotCategories) { Log.Info(LogTag, " none"); } }
public async Task <IActionResult> GetCategoriesAndSub([FromQuery] int?id) { const string loggerHeader = "GetCategoriesAndSub"; var result = new ApiJsonResult(); try { var userLogin = await _userService.GetCurrentUserLogin(HttpContext); _logService.Info($"{loggerHeader} Get product categories with tenantId {userLogin?.TenantId}"); var categoryFilter = new CategoryFilter { TenantId = userLogin?.TenantId, Id = id }; result.Data = await _categoryService.GetAllAndSub(categoryFilter); } catch (Exception ex) { result.Code = CodeModel.Fail; result.Message = ex.Message; } return(Ok(result)); }
public static IEnumerable <T> Matches <T>(this IEnumerable <T> combinations, string category, int? @class) where T : IDistanceCombination { return(from dc in combinations where CategoryFilter.IsMatch(dc.CategoryFilter, category) && ClassFilter.IsMatch(dc.ClassFilter, @class) select dc); }
public void CanGetLogFiltersByType() { ICollection <ILogFilter> filters = new List <ILogFilter>(); ICollection <string> categories = new List <string>(); categories.Add("cat1"); categories.Add("cat2"); categories.Add("cat3"); categories.Add("cat4"); filters.Add(new CategoryFilter("category", categories, CategoryFilterMode.AllowAllExceptDenied)); filters.Add(new PriorityFilter("priority", 100)); filters.Add(new LogEnabledFilter("enable", true)); LogWriter writer = new LogWriter(filters, new Dictionary <string, LogSource>(), new LogSource("errors"), "default"); CategoryFilter categoryFilter = writer.GetFilter <CategoryFilter>(); PriorityFilter priorityFilter = writer.GetFilter <PriorityFilter>(); LogEnabledFilter enabledFilter = writer.GetFilter <LogEnabledFilter>(); Assert.IsNotNull(categoryFilter); Assert.AreEqual(4, categoryFilter.CategoryFilters.Count); Assert.IsNotNull(priorityFilter); Assert.AreEqual(100, priorityFilter.MinimumPriority); Assert.IsNotNull(enabledFilter); Assert.IsTrue(enabledFilter.Enabled); }
public void OnlyApplicableEntriesAreWrittenWhenXmlListenerCategoryFilter() { File.Delete(Path.Combine(this.strPath, "XmlLogFile.xml")); LoggingConfiguration loggingConfiguration = BuildProgrammaticConfigForTrace(); this.UpdateConfigForXMLTL(loggingConfiguration); // Category Filters ICollection <string> categories = new List <string>(); categories.Add("BlockedByFilter"); var categoryFilter = new CategoryFilter("Category Filter", categories, CategoryFilterMode.DenyAllExceptAllowed); loggingConfiguration.Filters.Add(categoryFilter); this.writer = new LogWriter(loggingConfiguration); this.writer.Write("Test Logging XML 1", "General", 1); this.writer.Write("Test Logging XML 2", "BlockedByFilter", 2); this.writer.Dispose(); Assert.IsTrue(File.Exists(Path.Combine(this.strPath, "XmlLogFile.xml"))); string strFileData = LogFileReader.ReadFileWithoutLock(Path.Combine(this.strPath, "XmlLogFile.xml")); Assert.IsFalse(strFileData.Contains("<Message>Test Logging XML 1</Message>")); Assert.IsTrue(strFileData.Contains("<Message>Test Logging XML 2</Message>")); }
private object RunCategories(string name) { var invalid = new { text = "Please select a valid category/categories", status = "info" }; if (String.IsNullOrWhiteSpace(name)) { return new { message = invalid } } ; var ctgrs = name.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (ctgrs.Length == 0) { return new { message = invalid } } ; var validCtgrs = categories.Intersect(ctgrs.Select(HttpUtility.UrlDecode)).ToArray(); if (!validCtgrs.Any()) { return new { message = invalid } } ; var categoryFilter = new CategoryFilter(validCtgrs); return(RunTests(categoryFilter)); }
public void OnlyApplicableEntriesAreWrittenWhenRollingFlatFileCategoryFilter() { LoggingConfiguration loggingConfiguration = BuildProgrammaticConfigForTrace(); this.UpdateConfigForRollingFlatFileRollExistsIncrement(loggingConfiguration); // Category Filters ICollection <string> categories = new List <string>(); categories.Add("BlockedByFilter"); var categoryFilter = new CategoryFilter("Category Filter", categories, CategoryFilterMode.DenyAllExceptAllowed); loggingConfiguration.Filters.Add(categoryFilter); this.writer = new LogWriter(loggingConfiguration); this.writer.Write("Test Logging1", "General", 1); this.writer.Write("Test Logging2", "BlockedByFilter", 2); this.writer.Dispose(); Assert.IsTrue(File.Exists(Path.Combine(this.strPath, "RollingFlatFile.log"))); string strFileData = LogFileReader.ReadFileWithoutLock(Path.Combine(this.strPath, "RollingFlatFile.log")); Assert.IsFalse(strFileData.Contains("Message: Test Logging1")); Assert.IsTrue(strFileData.Contains("Message: Test Logging2")); }
public async Task <List <ProductDetail_CategoryDTO> > SingleListCategory([FromBody] ProductDetail_CategoryFilterDTO ProductDetail_CategoryFilterDTO) { CategoryFilter CategoryFilter = new CategoryFilter(); CategoryFilter.Skip = 0; CategoryFilter.Take = 20; CategoryFilter.OrderBy = CategoryOrder.Id; CategoryFilter.OrderType = OrderType.ASC; CategoryFilter.Selects = CategorySelect.ALL; CategoryFilter.Id = new LongFilter { Equal = ProductDetail_CategoryFilterDTO.Id }; CategoryFilter.Code = new StringFilter { StartsWith = ProductDetail_CategoryFilterDTO.Code }; CategoryFilter.Name = new StringFilter { StartsWith = ProductDetail_CategoryFilterDTO.Name }; CategoryFilter.ParentId = new LongFilter { Equal = ProductDetail_CategoryFilterDTO.ParentId }; CategoryFilter.Icon = new StringFilter { StartsWith = ProductDetail_CategoryFilterDTO.Icon }; List <Category> Categorys = await CategoryService.List(CategoryFilter); List <ProductDetail_CategoryDTO> ProductDetail_CategoryDTOs = Categorys .Select(x => new ProductDetail_CategoryDTO(x)).ToList(); return(ProductDetail_CategoryDTOs); }
public void CanParseCompoundCategory() { CategoryExpression expr = new CategoryExpression("One , Two; Three,Four"); CategoryFilter filter = (CategoryFilter)expr.Filter; Assert.That(filter.Categories, Is.EqualTo(new string[] { "One", "Two", "Three", "Four" })); }
public void CanParseSimpleCategory() { CategoryExpression expr = new CategoryExpression("Data"); CategoryFilter filter = (CategoryFilter)expr.Filter; Assert.That(filter.Categories, Is.EqualTo(new string[] { "Data" })); }
protected void RunClick(object sender, EventArgs args) { // Determine if any category filters have been selected StringCollection categories = new StringCollection(); for (int i = 0; i < cblCategories.Items.Count; i++) { if (cblCategories.Items[i].Selected) { categories.Add(cblCategories.Items[i].Value); } } if (categories.Count == 0) { for (int i = 0; i < cblCategories.Items.Count; i++) { categories.Add(cblCategories.Items[i].Value); } } string[] arCats = new string[categories.Count]; categories.CopyTo(arCats, 0); // Create a category filter ITestFilter filter = new CategoryFilter(arCats); TestResult result = null; result = m_testSuite.Run(this, filter); // Bind results to presentation gvResults.DataSource = m_results; gvResults.DataBind(); // Display statistics ltlStats.Text = string.Format("{0} out of {1} tests run in {2} seconds.", m_executedCount, result.Test.TestCount, result.Time); if (m_failedCount > 0) { ltlStats.Text += string.Format("<br/>{0} {1} failed", m_failedCount, m_failedCount == 1 ? "test" : "tests"); } int skipped = result.Test.TestCount - m_executedCount; if (skipped > 0) { ltlStats.Text += string.Format("<br/>{0} {1} skipped", skipped, skipped == 1 ? "test" : "tests"); } lblResult.Text = "Suite " + (result.IsSuccess ? "Passed" : "Failed"); if (result.IsSuccess) { lblResult.CssClass = "passLabel"; } else { lblResult.CssClass = "failLabel"; } }
public void CategoryFilter_SingleCategoryConstructor() { var filter = new CategoryFilter("Dummy"); Assert.False(filter.IsEmpty); Assert.That(filter.Match(dummyFixture)); Assert.False(filter.Match(anotherFixture)); }
public void RunExplicitTestByCategory() { CategoryFilter filter = new CategoryFilter("Special"); TestResult result = mockTestFixture.Run(NullListener.NULL, filter); ResultSummarizer summarizer = new ResultSummarizer(result); Assert.AreEqual(1, summarizer.TestsRun); }
public void CanParseExcludedCategories() { CategoryExpression expr = new CategoryExpression("-One,Two,Three"); NotFilter notFilter = (NotFilter)expr.Filter; CategoryFilter catFilter = (CategoryFilter)notFilter.BaseFilter; Assert.AreEqual(catFilter.Categories, new string[] { "One", "Two", "Three" }); }
protected void RunClick(object sender, EventArgs args) { // Determine if any category filters have been selected StringCollection categories = new StringCollection(); for (int i = 0; i < cblCategories.Items.Count; i++) { if (cblCategories.Items[i].Selected) categories.Add(cblCategories.Items[i].Value); } if (categories.Count == 0) { for (int i = 0; i < cblCategories.Items.Count; i++) { categories.Add(cblCategories.Items[i].Value); } } string[] arCats = new string[categories.Count]; categories.CopyTo(arCats, 0); // Create a category filter ITestFilter filter = new CategoryFilter(arCats); TestResult result = null; result = m_testSuite.Run(this, filter); // Bind results to presentation gvResults.DataSource = m_results; gvResults.DataBind(); // Display statistics ltlStats.Text = string.Format("{0} out of {1} tests run in {2} seconds.", m_executedCount, result.Test.TestCount, result.Time); if (m_failedCount > 0) ltlStats.Text += string.Format("<br/>{0} {1} failed", m_failedCount, m_failedCount == 1 ? "test" : "tests"); int skipped = result.Test.TestCount - m_executedCount; if (skipped > 0) ltlStats.Text += string.Format("<br/>{0} {1} skipped", skipped, skipped == 1 ? "test" : "tests"); lblResult.Text = "Suite " + (result.IsSuccess ? "Passed" : "Failed"); if (result.IsSuccess) lblResult.CssClass = "passLabel"; else lblResult.CssClass = "failLabel"; }
public void SetUp() { ICollection<string> categoryFilters = new string[] { "foo" }; categoryFilter = new CategoryFilter("category", categoryFilters, CategoryFilterMode.DenyAllExceptAllowed); priorityFilter = new PriorityFilter("priority", 5); enabledFilter = new LogEnabledFilter("enable", true); ICollection<ILogFilter> filters = new List<ILogFilter>(3); filters.Add(enabledFilter); filters.Add(categoryFilter); filters.Add(priorityFilter); handler = new MockLogFilterErrorHandler(true); filterHelper = new LogFilterHelper(filters, handler); log = CommonUtil.GetDefaultLogEntry(); }
protected void RunClick(object sender, EventArgs args) { var categories = from ListItem item in cblCategories.Items where item.Selected select item.Value; if(!categories.Any()) categories = from ListItem item in cblCategories.Items select item.Value; // Create a category filter var filter = new CategoryFilter(categories.ToArray()); var runner = new SimpleTestRunner(); runner.Load(_testPackage); var result = runner.Run(this, filter, true, LoggingThreshold.All); // Bind results to presentation gvResults.DataSource = _results; gvResults.DataBind(); // Display statistics ltlStats.Text = string.Format("{0} out of {1} tests run in {2} seconds.", _executedCount, result.Test.TestCount, result.Time); if (_failedCount > 0) ltlStats.Text += string.Format("<br/>{0} {1} failed", _failedCount, _failedCount == 1 ? "test" : "tests"); var skipped = result.Test.TestCount - _executedCount; if (skipped > 0) ltlStats.Text += string.Format("<br/>{0} {1} skipped", skipped, skipped == 1 ? "test" : "tests"); lblResult.Text = "Suite " + (result.IsSuccess ? "Passed" : "Failed"); if (result.IsSuccess) lblResult.CssClass = "passLabel"; else lblResult.CssClass = "failLabel"; }
private CategoryFilter GetCategoryFilter() { CategoryFilter filter = new CategoryFilter( token ); while( GetToken() == "," || token == ";" ) filter.AddCategory( GetToken() ); return filter; }
public static TestFilter FromXml(string xmlText) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlText); XmlNode topNode = doc.FirstChild; if (topNode.Name != "filter") throw new Exception("Expected filter element at top level"); // Initially, an empty filter TestFilter result = TestFilter.Empty; bool isEmptyResult = true; XmlNodeList testNodes = topNode.SelectNodes("tests/test"); XmlNodeList includeNodes = topNode.SelectNodes("include/category"); XmlNodeList excludeNodes = topNode.SelectNodes("exclude/category"); if (testNodes.Count > 0) { SimpleNameFilter nameFilter = new SimpleNameFilter(); foreach (XmlNode testNode in topNode.SelectNodes("tests/test")) nameFilter.Add(testNode.InnerText); result = nameFilter; isEmptyResult = false; } if (includeNodes.Count > 0) { //CategoryFilter includeFilter = new CategoryFilter(); //foreach (XmlNode includeNode in includeNodes) // includeFilter.AddCategory(includeNode.InnerText); // Temporarily just look at the first element XmlNode includeNode = includeNodes[0]; TestFilter includeFilter = new CategoryExpression(includeNode.InnerText).Filter; if (isEmptyResult) result = includeFilter; else result = new AndFilter(result, includeFilter); isEmptyResult = false; } if (excludeNodes.Count > 0) { CategoryFilter categoryFilter = new CategoryFilter(); foreach (XmlNode excludeNode in excludeNodes) categoryFilter.AddCategory(excludeNode.InnerText); TestFilter excludeFilter = new NotFilter(categoryFilter); if (isEmptyResult) result = excludeFilter; else result = new AndFilter(result, excludeFilter); isEmptyResult = false; } return result; }
/// <summary> /// Runs the tests and sets up the formatters. /// </summary> protected override void ExecuteTask() { if (FormatterElements.Count == 0) { FormatterElement defaultFormatter = new FormatterElement(); defaultFormatter.Project = Project; defaultFormatter.NamespaceManager = NamespaceManager; defaultFormatter.Type = FormatterType.Plain; defaultFormatter.UseFile = false; FormatterElements.Add(defaultFormatter); Log(Level.Warning, "No <formatter .../> element was specified." + " A plain-text formatter was added to prevent losing output of the" + " test results."); Log(Level.Warning, "Add a <formatter .../> element to the" + " <nunit2> task to prevent this warning from being output and" + " to ensure forward compatibility with future revisions of NAnt."); } LogWriter logWriter = new LogWriter(this, Level.Info, CultureInfo.InvariantCulture); EventListener listener = new EventCollector(logWriter, logWriter); foreach (NUnit2Test testElement in Tests) { ITestFilter categoryFilter = null; // include or exclude specific categories string categories = testElement.Categories.Includes.ToString(); if (!StringUtils.IsNullOrEmpty(categories)) { categoryFilter = new CategoryFilter(categories.Split(',')); } else { categories = testElement.Categories.Excludes.ToString(); if (!StringUtils.IsNullOrEmpty(categories)) { categoryFilter = new NotFilter(new CategoryFilter(categories.Split(','))); } } foreach (string testAssembly in testElement.TestAssemblies) { NUnit2TestDomain domain = new NUnit2TestDomain(); try { TestRunner runner = domain.CreateRunner( new FileInfo(testAssembly), testElement.AppConfigFile, testElement.References.FileNames); TestPackage package = new TestPackage(testAssembly); bool test = runner.Load(package); if (!test) { Log(Level.Warning, "Assembly \"{0}\" contains no tests.", testAssembly); continue; } // run test TestResult result; if(categoryFilter != null) { result = runner.Run(listener, categoryFilter); } else { result = runner.Run(listener); } // flush test output to log logWriter.Flush(); // format test results using specified formatters FormatResult(testElement, result); if (result.IsFailure && (testElement.HaltOnFailure || HaltOnFailure)) { throw new BuildException("Tests Failed.", Location); } } catch (BuildException) { // re-throw build exceptions throw; } catch (Exception ex) { if (!FailOnError) { // just log error and continue with next test Log(Level.Error, LogPrefix + "NUnit Error: " + ex.ToString()); continue; } Version nunitVersion = typeof(TestResult).Assembly.GetName().Version; throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failure executing test(s). If you assembly is not built using" + " NUnit version {0}, then ensure you have redirected assembly" + " bindings. Consult the documentation of the <nunit2> task" + " for more information.", nunitVersion), Location, ex); } finally { domain.Unload(); // flush test output to log logWriter.Flush(); } } } }
public void Restore(TestSuiteTreeView tree) { if (ShowCheckBoxes != tree.CheckBoxes) tree.CheckBoxes = ShowCheckBoxes; foreach (VisualTreeNode visualNode in Nodes) visualNode.Restore(tree); if (SelectedNode != null) { TestSuiteTreeNode treeNode = tree[SelectedNode]; if (treeNode != null) tree.SelectedNode = treeNode; } if (TopNode != null) { TestSuiteTreeNode treeNode = tree[TopNode]; if (treeNode != null) tree.TryToSetTopNode(treeNode); } if (this.SelectedCategories != null) { TestFilter filter = new CategoryFilter( this.SelectedCategories.Split( new char[] { ',' } ) ); if ( this.ExcludeCategories ) filter = new NotFilter( filter ); tree.CategoryFilter = filter; } tree.Select(); }
protected ITestFilter ConstructFilter() { var categories = (from ListItem item in cblCategories.Items where item.Selected select item.Value).ToArray(); var methodNames = (from ListItem item in cblMethods.Items where item.Selected select item.Value).ToArray(); if (!categories.Any() && !methodNames.Any()) return TestFilter.Empty; var categoryFilter = new CategoryFilter(categories); var methodFilter = new SimpleNameFilter(methodNames); return new OrFilter(categoryFilter, methodFilter); }
/// <summary> /// Runs the tests and sets up the formatters. /// </summary> protected override void ExecuteTask() { if (FormatterElements.Count == 0) { FormatterElement defaultFormatter = new FormatterElement(); defaultFormatter.Project = Project; defaultFormatter.NamespaceManager = NamespaceManager; defaultFormatter.Type = FormatterType.Plain; defaultFormatter.UseFile = false; FormatterElements.Add(defaultFormatter); Log(Level.Warning, "No <formatter .../> element was specified." + " A plain-text formatter was added to prevent losing output of the" + " test results."); Log(Level.Warning, "Add a <formatter .../> element to the" + " <nunit2> task to prevent this warning from being output and" + " to ensure forward compatibility with future revisions of NAnt."); } LogWriter logWriter = new LogWriter(this, Level.Info, CultureInfo.InvariantCulture); EventListener listener = GetListener(logWriter); foreach (NUnit2Test testElement in Tests) { // Setup the test filter var to setup include/exclude filters. ITestFilter testFilter = null; // If the include categories contains values, setup the category // filter with the include categories. string includes = testElement.Categories.Includes.ToString(); if (!String.IsNullOrEmpty(includes)) { testFilter = new CategoryFilter(includes.Split(',')); } else { // If the include categories does not have includes but // contains excludes, setup the category filter with the excludes // and use the Not filter to tag the categories for exclude. string excludes = testElement.Categories.Excludes.ToString(); if (!String.IsNullOrEmpty(excludes)) { ITestFilter excludeFilter = new CategoryFilter(excludes.Split(',')); testFilter = new NotFilter(excludeFilter); } else { // If the categories do not contain includes or excludes, // assign the testFilter var with an empty filter. testFilter = TestFilter.Empty; } } foreach (string testAssembly in testElement.TestAssemblies) { // Setup the NUnit2TestDomain var. NUnit2TestDomain domain = new NUnit2TestDomain(); // Setup the TestPackage var to use with the testrunner var TestPackage package = new TestPackage(testAssembly); try { // Create the TestRunner var TestRunner runner = domain.CreateRunner( new FileInfo(testAssembly), testElement.AppConfigFile, testElement.References.FileNames); // If the name of the current test element is not null, // use it for the package test name. if (!String.IsNullOrEmpty(testElement.TestName)) { package.TestName = testElement.TestName; } // Bool var containing the result of loading the test package // in the TestRunner var. bool successfulLoad = runner.Load(package); // If the test package load was successful, proceed with the // testing. if (successfulLoad) { // If the runner does not contain any tests, proceed // to the next assembly. if (runner.Test == null) { Log(Level.Warning, "Assembly \"{0}\" contains no tests.", testAssembly); continue; } // Setup and run tests TestResult result = runner.Run(listener, testFilter, true, GetLoggingThreshold()); // flush test output to log logWriter.Flush(); // format test results using specified formatters FormatResult(testElement, result); if (result.IsFailure && (testElement.HaltOnFailure || HaltOnFailure)) { throw new BuildException("Tests Failed.", Location); } } else { // If the package load failed, throw a build exception. throw new BuildException("Test Package Load Failed.", Location); } } catch (BuildException) { // re-throw build exceptions throw; } catch (Exception ex) { if (!FailOnError) { // just log error and continue with next test // TODO: (RMB) Need to make sure that this is the correct way to proceed with displaying NUnit errors. string logMessage = String.Concat("[", Name, "] NUnit Error: ", ex.ToString()); Log(Level.Error, logMessage.PadLeft(Project.IndentationSize)); continue; } Version nunitVersion = typeof(TestResult).Assembly.GetName().Version; throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failure executing test(s). If you assembly is not built using" + " NUnit version {0}, then ensure you have redirected assembly" + " bindings. Consult the documentation of the <nunit2> task" + " for more information.", nunitVersion), Location, ex); } finally { domain.Unload(); // flush test output to log logWriter.Flush(); } } } }
public int Execute( ConsoleOptions options ) { XmlTextReader transformReader = GetTransformReader(options); if(transformReader == null) return 3; TextWriter outWriter = Console.Out; if ( options.isOut ) { StreamWriter outStreamWriter = new StreamWriter( options.output ); outStreamWriter.AutoFlush = true; outWriter = outStreamWriter; } TextWriter errorWriter = Console.Error; if ( options.isErr ) { StreamWriter errorStreamWriter = new StreamWriter( options.err ); errorStreamWriter.AutoFlush = true; errorWriter = errorStreamWriter; } TestRunner testRunner = MakeRunnerFromCommandLine( options ); try { if (testRunner.Test == null) { testRunner.Unload(); Console.Error.WriteLine("Unable to locate fixture {0}", options.fixture); return 2; } EventCollector collector = new EventCollector( options, outWriter, errorWriter ); TestFilter catFilter = TestFilter.Empty; if (options.HasInclude) { Console.WriteLine( "Included categories: " + options.include ); catFilter = new CategoryFilter( options.IncludedCategories ); } if ( options.HasExclude ) { Console.WriteLine( "Excluded categories: " + options.exclude ); TestFilter excludeFilter = new NotFilter( new CategoryFilter( options.ExcludedCategories ) ); if ( catFilter.IsEmpty ) catFilter = excludeFilter; else catFilter = new AndFilter( catFilter, excludeFilter ); } TestResult result = null; string savedDirectory = Environment.CurrentDirectory; TextWriter savedOut = Console.Out; TextWriter savedError = Console.Error; try { result = testRunner.Run( collector, catFilter ); } finally { outWriter.Flush(); errorWriter.Flush(); if ( options.isOut ) outWriter.Close(); if ( options.isErr ) errorWriter.Close(); Environment.CurrentDirectory = savedDirectory; Console.SetOut( savedOut ); Console.SetError( savedError ); } Console.WriteLine(); string xmlOutput = CreateXmlOutput( result ); if (options.xmlConsole) { Console.WriteLine(xmlOutput); } else { try { //CreateSummaryDocument(xmlOutput, transformReader ); XmlResultTransform xform = new XmlResultTransform( transformReader ); xform.Transform( new StringReader( xmlOutput ), Console.Out ); } catch( Exception ex ) { Console.WriteLine( "Error: {0}", ex.Message ); return 3; } } // Write xml output here string xmlResultFile = options.IsXml ? options.xml : "TestResult.xml"; using ( StreamWriter writer = new StreamWriter( xmlResultFile ) ) { writer.Write(xmlOutput); } //if ( testRunner != null ) // testRunner.Unload(); if ( collector.HasExceptions ) { collector.WriteExceptions(); return 2; } return result.IsFailure ? 1 : 0; } finally { testRunner.Unload(); } }
public void Restore(TestSuiteTreeView treeView) { treeView.CheckBoxes = this.ShowCheckBoxes; foreach (VisualTreeNode visualNode in this.Nodes) { TestSuiteTreeNode treeNode = treeView[visualNode.UniqueName]; if (treeNode != null) { if (treeNode.IsExpanded != visualNode.Expanded) treeNode.Toggle(); treeNode.Checked = visualNode.Checked; } } if (this.SelectedNode != null) { TestSuiteTreeNode treeNode = treeView[this.SelectedNode]; if (treeNode != null) treeView.SelectedNode = treeNode; } if (this.TopNode != null) { TestSuiteTreeNode treeNode = treeView[this.TopNode]; if (treeNode != null) treeView.TopNode = treeNode; } if (this.SelectedCategories != null) { TestFilter filter = new CategoryFilter(this.SelectedCategories.Split(new char[] { ',' })); if (this.ExcludeCategories) filter = new NotFilter(filter); treeView.CategoryFilter = filter; } treeView.Select(); }
private object RunCategories(string name) { var invalid = new { text = "Please select a valid category/categories", status = "info" }; if (String.IsNullOrWhiteSpace(name)) return new { message = invalid }; var ctgrs = name.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (ctgrs.Length == 0) return new { message = invalid }; var validCtgrs = categories.Intersect(ctgrs.Select(HttpUtility.UrlDecode)).ToArray(); if (!validCtgrs.Any()) return new { message = invalid }; var categoryFilter = new CategoryFilter(validCtgrs); return RunTests(categoryFilter); }
private void RestoreVisualState( VisualState visualState ) { this.CheckBoxes = visualState.ShowCheckBoxes; foreach (VisualTreeNode visualNode in visualState.Nodes) { TestSuiteTreeNode treeNode = this[visualNode.UniqueName]; if (treeNode != null) { if (treeNode.IsExpanded != visualNode.Expanded) treeNode.Toggle(); treeNode.Checked = visualNode.Checked; } } if (visualState.SelectedNode != null) { TestSuiteTreeNode treeNode = this[visualState.SelectedNode]; if (treeNode != null) this.SelectedNode = treeNode; } if (visualState.TopNode != null) { TestSuiteTreeNode treeNode = this[visualState.TopNode]; if (treeNode != null) TryToSetTopNode(treeNode); } if (visualState.SelectedCategories != null) { TestFilter filter = new CategoryFilter(visualState.SelectedCategories.Split(new char[] { ',' })); if (visualState.ExcludeCategories) filter = new NotFilter(filter); this.CategoryFilter = filter; } this.Select(); }