public FB_AnyToUnionValue(ErrorItems errorItems, string testFunctionBlockInstance) : base(errorItems, testFunctionBlockInstance) { Test_BOOL(); Test_BIT(); Test_BYTE(); Test_WORD(); Test_DWORD(); Test_LWORD(); Test_SINT(); Test_INT(); Test_DINT(); Test_LINT(); Test_USINT(); Test_UINT(); Test_UDINT(); Test_ULINT(); Test_REAL(); Test_LREAL(); Test_STRING(); Test_STRING_2(); Test_WSTRING(); Test_TIME(); Test_DATE(); Test_DATE_AND_TIME(); Test_TIME_OF_DAY(); Test_LTIME(); }
public FB_AssertTrueFalse(ErrorItems errorItems, string testFunctionBlockInstance) : base(errorItems, testFunctionBlockInstance) { AssertThatINTsAreEqual(); AssertThatINTsAreNotEqual(); AssertThatWORDsAreEqual(); AssertThatWORDsAreNotEqual(); }
private async void ErrorItemsVisible_Changed(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (Animation) { return; } if (e.PropertyName == "IsVisible") { if (ErrorItems.IsVisible) { Animation = true; CategoryListView.IsPullToRefreshEnabled = false; ErrorItems.TranslationX = -300; await ErrorItems.TranslateTo(ErrorItems.TranslationX + 320, ErrorItems.TranslationY, 150); await ErrorItems.TranslateTo(ErrorItems.TranslationX - 50, ErrorItems.TranslationY, 40); await ErrorItems.TranslateTo(ErrorItems.TranslationX + 50, ErrorItems.TranslationY, 50); await ErrorItems.TranslateTo(ErrorItems.TranslationX - 20, ErrorItems.TranslationY, 40); Animation = false; } else { ErrorItems.TranslationX = -300; } } }
/// <summary> Listen for any errors and show the standard feedback screen to the user. </summary> /// <param name="value"> The value. </param> public void ShowErrors(object value) { ErrorItems errorItems = (ErrorItems)value; string message = string.Join("\n", errorItems.Errors.Select(e => e.FriendlyMessage)); // If error is thrown but message string is empty then do not display any messagebox if (string.IsNullOrEmpty(message)) { return; } MessageBoxImage icon = MessageBoxImage.Information; if (errorItems.Errors.Any(ei => ei.ErrorDisplayType == ErrorDisplayType.Error)) { icon = MessageBoxImage.Error; } else if (errorItems.Errors.Any(ei => ei.ErrorDisplayType == ErrorDisplayType.Warning)) { icon = MessageBoxImage.Warning; } //IMessageBoxService messageBoxService = container.Resolve<IMessageBoxService>(); //messageBoxService.ShowDialog(message, errorItems.Caption, MessageBoxButton.OK, icon); }
private bool waitForBuildAndCheckErrors(IWorker worker, out ErrorItems errorItems) { bool buildSucceeded = false; vsBuildState state = dte.Solution.SolutionBuild.BuildState; while (state == vsBuildState.vsBuildStateInProgress) { System.Threading.Thread.Sleep(500); if (worker.CancellationPending) { dte.ExecuteCommand("Build.Cancel"); } state = dte.Solution.SolutionBuild.BuildState; } buildSucceeded = (dte.Solution.SolutionBuild.LastBuildInfo == 0 && state == vsBuildState.vsBuildStateDone); // The ErrorList is not significant for the succeeded Build!!! // Because the PLC Project can contain errors within not used types. // Relevant is only the "LastBuildInfo" object that contains the numer of failed project compilations! ErrorList errorList = dte.ToolWindows.ErrorList; errorItems = errorList.ErrorItems; return(buildSucceeded); }
public FB_ArrayPrimitiveTypes(ErrorItems errorItems, string testFunctionBlockInstance) : base(errorItems, testFunctionBlockInstance) { Test_BOOL_Array_Equals(); Test_BOOL_Array_DifferInSize(); Test_BOOL_Array_DifferInContent(); Test_BYTE_Array_Equals(); Test_BYTE_Array_DifferInSize(); Test_BYTE_Array_DifferInContent(); Test_DINT_Array_Equals(); Test_DINT_Array_DifferInSize(); Test_DINT_Array_DifferInContent(); Test_DWORD_Array_Equals(); Test_DWORD_Array_DifferInSize(); Test_DWORD_Array_DifferInContent(); Test_INT_Array_Equals(); Test_INT_Array_DifferInSize(); Test_INT_Array_DifferInContent(); Test_LINT_Array_Equals(); Test_LINT_Array_DifferInSize(); Test_LINT_Array_DifferInContent(); Test_LREAL_Array_Equals(); Test_LREAL_Array_DifferInSize(); Test_LREAL_Array_DifferInContent(); Test_LREAL_Array2d_Equals(); Test_LREAL_Array2d_DifferInSize(); Test_LREAL_Array2d_DifferInContent(); Test_LREAL_Array3d_Equals(); Test_LREAL_Array3d_DifferInSize(); Test_LREAL_Array3d_DifferInContent(); Test_LWORD_Array_Equals(); Test_LWORD_Array_DifferInSize(); Test_LWORD_Array_DifferInContent(); Test_REAL_Array_Equals(); Test_REAL_Array_DifferInSize(); Test_REAL_Array_DifferInContent(); Test_REAL_Array2d_Equals(); Test_REAL_Array2d_DifferInSize(); Test_REAL_Array2d_DifferInContent(); Test_REAL_Array3d_Equals(); Test_REAL_Array3d_DifferInSize(); Test_REAL_Array3d_DifferInContent(); Test_SINT_Array_Equals(); Test_SINT_Array_DifferInSize(); Test_SINT_Array_DifferInContent(); Test_UDINT_Array_Equals(); Test_UDINT_Array_DifferInSize(); Test_UDINT_Array_DifferInContent(); Test_UINT_Array_Equals(); Test_UINT_Array_DifferInSize(); Test_UINT_Array_DifferInContent(); Test_ULINT_Array_Equals(); Test_ULINT_Array_DifferInSize(); Test_ULINT_Array_DifferInContent(); Test_USINT_Array_Equals(); Test_USINT_Array_DifferInSize(); Test_USINT_Array_DifferInContent(); Test_WORD_Array_Equals(); Test_WORD_Array_DifferInSize(); Test_WORD_Array_DifferInContent(); }
void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { Exception ex = e.Exception; if (ex.InnerException != null) { ex = ex.InnerException; } string message = ex.Message; message += Environment.NewLine + "Stack Trace:"; message += Environment.NewLine + ex.StackTrace; ErrorItems errors = new ErrorItems(); errors.Errors.Add( new ErrorItem { ErrorDisplayType = ErrorDisplayType.Error, FriendlyMessage = message, Error = ex, }); eventAggregator = Container.Resolve <IEventAggregator>(); eventAggregator.GetEvent <Module.Shared.Events.CommonEvents.ErrorOccuredEvent>().Publish(errors); Container.Resolve <IBusyService>().HideAllBusy(); logService.Error(message); e.Handled = true; }
// adds the mappings between errors in the generated parser-file and their corresponding position in the grammar file (semantic actions). private void OnBuildDone(vsBuildScope Scope, vsBuildAction Action) { DTE2 dte = (DTE2)GetService(typeof(DTE)); ErrorItems errors = dte.ToolWindows.ErrorList.ErrorItems; Hashtable mapCache = new Hashtable(); bool grammarErrorFound = false; for (uint i = 1; i <= errors.Count; i++) { ErrorItem error = errors.Item(i); string fn = Path.GetFileName(error.FileName); string dir = Path.GetDirectoryName(error.FileName); if (fn.ToLower() == "parser.cs") { string atgmap = Path.Combine(dir, "parser.atgmap"); Mapping map = null; if (mapCache.ContainsKey(atgmap)) { map = (Mapping)mapCache[atgmap]; } else { if (File.Exists(atgmap)) { map = new Mapping(); map.Read(atgmap); mapCache[atgmap] = map; } } if (map != null) { int line, column; if (map.Get(error.Line - 1, error.Column - 1, out line, out column)) { ErrorTask task = new ErrorTask(); task.ErrorCategory = TaskErrorCategory.Error; task.Priority = TaskPriority.Normal; task.Text = error.Description; task.Column = column; task.Line = line; task.Document = map.Grammar; task.Navigate += NavigateDocument; errorListProvider.Tasks.Add(task); grammarErrorFound = true; } } } } if (grammarErrorFound) { errorListProvider.Show(); } }
/// <summary> /// Añade un elemento de error /// </summary> internal void AddError(MessageError error) { // Añade el elemento al error ErrorItems.Add(error); // Si tiene demasiados elementos de log quita el primero if (ErrorItems.Count > 1000) { ErrorItems.RemoveAt(0); } }
public ErrorListNodeFactory(ErrorItems items, DTE2 dte) { _dte = dte; _items = new List <ErrorItem>(items.Count); for (int i = 0; i < items.Count; ++i) { _items.Add(items.Item(i + 1)); } }
public ErrorListNodeFactory(ErrorItems items, DTE2 dte) { _dte = dte; _items = new List<ErrorItem>(items.Count); for (int i = 0; i < items.Count; ++i) { _items.Add(items.Item(i + 1)); } }
private bool CompileProject(IWorker worker, out ErrorItems errors) { bool buildSucceeded = false; if (worker.CancellationPending) { throw new Exception("Execution cancelled!"); } worker.ProgressStatus = "Compiling project ..."; dte.Solution.SolutionBuild.Build(true); buildSucceeded = waitForBuildAndCheckErrors(worker, out errors); if (!buildSucceeded) { int overallMessages = errors.Count; int errorCount = 0; int warningCount = 0; int messageCount = 0; for (int i = 1; i <= overallMessages; i++) // List is starting from 1!!! { ErrorItem item = errors.Item(i); if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh) { errorCount++; worker.ProgressStatus = "Compiler error: " + item.Description; } else if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelMedium) { warningCount++; worker.ProgressStatus = "Compiler warning: " + item.Description; } else if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelLow) { messageCount++; worker.ProgressStatus = "Compiler message: " + item.Description; } } } else { worker.ProgressStatus = "Build Succeeded!"; } if (worker.CancellationPending) { throw new Exception("Execution cancelled!"); } return(buildSucceeded); }
public async Task UpdateOutputFilesDoesNotGenerateWarningWhenDefaultOutputFileIsEmpty() // Because there may be nothing developer can do about it { await UIThreadDispatcher.Invoke <Task>(async delegate { this.output.File = string.Empty; this.output.Content.Clear(); this.output.Content.Append(WhiteSpaceText); this.provider.UpdateOutputFiles(this.input.FileNames[1], new[] { this.output }); await this.SimulateCustomTool(); Assert.IsFalse(ErrorItems.Any(item => item.FileName == this.input.FileNames[1])); }); }
public IEnumerable <Error> AddNew(ErrorItems errorItems) { int N1 = _errors.Count + 1; int N2 = errorItems.Count; for (int i = N1; i <= N2; i++) { var item = errorItems.Item(i); _errors.Add(new Error(item)); } return(_errors.GetRange(N1 - 1, N2 + 1 - N1)); }
private List <ErrorItem> GetErrors() { ErrorItems errors = envDte2.ToolWindows.ErrorList.ErrorItems; List <ErrorItem> listOfSelecteedItems = new List <ErrorItem>(); for (int i = 1; i <= errors.Count; i++) { ErrorItem item = errors.Item(i); listOfSelecteedItems.Add(item); } return(listOfSelecteedItems); }
public async Task UpdateOutputFilesGeneratesWarningWhenAdditionalOutputFileIsEmpty() // To encourage developer to cleanup their code generator { await UIThreadDispatcher.Invoke <Task>(async delegate { this.output.Content.Clear(); this.output.Content.Append(WhiteSpaceText); this.provider.UpdateOutputFiles(this.input.FileNames[1], new[] { this.output }); await this.SimulateCustomTool(); ErrorItem warning = ErrorItems.Single(item => item.FileName == this.input.FileNames[1]); StringAssert.Contains(warning.Description, this.output.Path); Assert.AreEqual(vsBuildErrorLevel.vsBuildErrorLevelMedium, warning.ErrorLevel); }); }
public void TestCompileAspNet(string version, string appType) { string projectName = $"TestGcpAspNet{appType}"; CreateProjectFromTemplate(projectName, "NetFramework", "Gcp.AspNet.vstemplate", version, appType); Solution.SolutionBuild.Build(true); Assert.AreEqual(vsBuildState.vsBuildStateDone, Solution.SolutionBuild.BuildState, projectName); Assert.AreEqual(0, Solution.SolutionBuild.LastBuildInfo, $"{projectName} build output:{Environment.NewLine}{GetBuildOutput()}"); string descriptions = string.Join( Environment.NewLine, ErrorItems.Select(e => e.Project + ":" + e.Description)); Assert.AreEqual(0, ErrorItems.Count(e => e.Project == projectName), $"{projectName} error descriptions:{Environment.NewLine}{descriptions}"); }
public FB_PrimitiveTypes(ErrorItems errorItems, string testFunctionBlockInstance) : base(errorItems, testFunctionBlockInstance) { Test_ANY_Equals(); Test_ANY_Differ_DataType(); Test_BOOL_Equals(); Test_BOOL_Differ(); Test_BYTE_Equals(); Test_BYTE_Differ(); Test_DATE_AND_TIME_Equals(); Test_DATE_AND_TIME_Differ(); Test_DATE_Equals(); Test_DATE_Differ(); Test_DINT_Equals(); Test_DINT_Differ(); Test_DWORD_Equals(); Test_DWORD_Differ(); Test_INT_Equals(); Test_INT_Differ(); Test_LINT_Equals(); Test_LINT_Differ(); Test_LREAL_Equals(); Test_LREAL_Differ(); Test_LTIME_Equals(); Test_LTIME_Differ(); Test_LWORD_Equals(); Test_LWORD_Differ(); Test_REAL_Equals(); Test_REAL_Differ(); Test_SINT_Equals(); Test_SINT_Differ(); Test_STRING_Equals(); Test_STRING_Differ(); Test_TIME_Equals(); Test_TIME_Differ(); Test_TIME_OF_DAY_Equals(); Test_TIME_OF_DAY_Differ(); Test_UDINT_Equals(); Test_UDINT_Differ(); Test_UINT_Equals(); Test_UINT_Differ(); Test_ULINT_Equals(); Test_ULINT_Differ(); Test_USINT_Equals(); Test_USINT_Differ(); Test_WORD_Equals(); Test_WORD_Differ(); }
void mBuildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action) { if (!TaskbarManager.IsPlatformSupported) { return; } mWindowsTaskBar.SetProgressState(TaskbarProgressBarState.NoProgress); if (mBuildError) { mWindowsTaskBar.SetOverlayIcon(IconTheme.IconBuildFail(mSettings.Theme), "Build Failed"); } else { bool buildWarnings = false; if (mSettings.ShowWarnings) { try { ErrorItems errorList = (mDTE as EnvDTE80.DTE2).ToolWindows.ErrorList.ErrorItems; for (int i = 1; i <= errorList.Count; i++) { ErrorItem e = errorList.Item(i); if (e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelMedium) { buildWarnings = true; break; } } } catch { } } if (buildWarnings) { mWindowsTaskBar.SetOverlayIcon(IconTheme.IconBuildWarning(mSettings.Theme), "Build Successful with Warnings"); } else { mWindowsTaskBar.SetOverlayIcon(IconTheme.IconBuildOK(mSettings.Theme), "Build Successful"); } } }
public void printErrors() { Dictionary <vsBuildErrorLevel, String> errorLevel = new Dictionary <vsBuildErrorLevel, String>() { { vsBuildErrorLevel.vsBuildErrorLevelHigh, "Error" }, { vsBuildErrorLevel.vsBuildErrorLevelMedium, "Warning" }, { vsBuildErrorLevel.vsBuildErrorLevelLow, "Info" } }; ErrorItems errorItems = dte.ToolWindows.ErrorList.ErrorItems; var errors = from i in Enumerable.Range(1, errorItems.Count) select errorItems.Item(i); var newErrors = errors.Except(lastErrors, new ErrorComparer()); newErrors.ToList().ForEach(error => Console.WriteLine("Build " + errorLevel[error.ErrorLevel] + ": " + error.Description)); lastErrors = errors.ToList(); }
internal void FromEntries(Entries es) { SetAllNull(); SLMissingItem mi; SLNumberItem ni; SLErrorItem ei; SLStringItem si; using (var oxr = OpenXmlReader.Create(es)) { while (oxr.Read()) { if (oxr.ElementType == typeof(MissingItem)) { mi = new SLMissingItem(); mi.FromMissingItem((MissingItem)oxr.LoadCurrentElement()); Items.Add(new SLEntriesItemsTypeIndexPair(SLEntriesItemsType.Missing, MissingItems.Count)); MissingItems.Add(mi); } else if (oxr.ElementType == typeof(NumberItem)) { ni = new SLNumberItem(); ni.FromNumberItem((NumberItem)oxr.LoadCurrentElement()); Items.Add(new SLEntriesItemsTypeIndexPair(SLEntriesItemsType.Number, NumberItems.Count)); NumberItems.Add(ni); } else if (oxr.ElementType == typeof(ErrorItem)) { ei = new SLErrorItem(); ei.FromErrorItem((ErrorItem)oxr.LoadCurrentElement()); Items.Add(new SLEntriesItemsTypeIndexPair(SLEntriesItemsType.Error, ErrorItems.Count)); ErrorItems.Add(ei); } else if (oxr.ElementType == typeof(StringItem)) { si = new SLStringItem(); si.FromStringItem((StringItem)oxr.LoadCurrentElement()); Items.Add(new SLEntriesItemsTypeIndexPair(SLEntriesItemsType.String, StringItems.Count)); StringItems.Add(si); } } } }
// invoked when plus button is clicked private void Button_Click(object sender, RoutedEventArgs e) { // initalize the select window selected items selectWindow.SelectWindowSelectedItems = CopySelectedItems(); selectWindow.ShowDialog(); if (selectWindow.SelectWindowResult) { // reset flag selectWindow.SelectWindowResult = false; // save the new selection SaveSelectedItems(selectWindow.SelectWindowSelectedItems); // convert to text also ConvertSelectedItemstoText(); // clear any validation errors as no errors ClearValidationError(); // clear error items as none will exist ErrorItems.Clear(); } }
public void TestCompileAspNetCore(string version, string appType) { string projectName = $"TestGcpAspNetCore{appType}{version.Replace(".", "").Replace("-", "")}"; CreateProjectFromTemplate(projectName, "NetCore", "Gcp.AspNetCore.vstemplate", version, appType); RestorePackages(Path.Combine(SolutionFolderPath, projectName)); Solution.SolutionBuild.Build(true); Assert.AreEqual(vsBuildState.vsBuildStateDone, Solution.SolutionBuild.BuildState, projectName); Assert.AreEqual( 0, Solution.SolutionBuild.LastBuildInfo, $"{projectName} build output:{Environment.NewLine}{GetBuildOutput()}"); string descriptions = string.Join( Environment.NewLine, ErrorItems.Select(e => e.Project + ":" + e.Description)); Assert.AreEqual( 0, ErrorItems.Count(e => e.Project == $"Test{projectName}Project"), $"{projectName} error descriptions:{Environment.NewLine}{descriptions}"); }
public ErrorTagger(DTE dte, ITextBuffer buffer) { _DTE = dte; _textBuffer = buffer; _textDocument = _textBuffer.Properties[typeof(ITextDocument)] as ITextDocument; _errorList = (_DTE as EnvDTE80.DTE2).ToolWindows.ErrorList.ErrorItems; _updateTimer = new Timer(500); _updateTimer.AutoReset = false; _updateTimer.Elapsed += (s, e) => UpdateErrorList(); _updateTimer.Start(); buffer.Changed += (i, j) => { _updateTimer.Stop(); _updateTimer.Start(); }; _taskListEvents = dte.Events.TaskListEvents; _taskListEvents.TaskAdded += (i) => { _updateTimer.Stop(); _updateTimer.Start(); }; _taskListEvents.TaskRemoved += (i) => { _updateTimer.Stop(); _updateTimer.Start(); }; _buildEvents = dte.Events.BuildEvents; _buildEvents.OnBuildDone += (e, p) => { _updateTimer.Stop(); _updateTimer.Start(); }; }
public void TestCompile() { TemplateName = Convert.ToString(TestContext.DataRow[0]); bool isCoreTemplate = Convert.ToBoolean(TestContext.DataRow[1]); CreateProjectFromTemplate(); if (isCoreTemplate) { RestorePackages(); } Solution.SolutionBuild.Build(true); Assert.AreEqual(vsBuildState.vsBuildStateDone, Solution.SolutionBuild.BuildState, TemplateName); Assert.AreEqual(0, Solution.SolutionBuild.LastBuildInfo, $"{TemplateName} build output:{Environment.NewLine}{GetBuildOutput()}"); string descriptions = string.Join( Environment.NewLine, ErrorItems.Select(e => e.Project + ":" + e.Description)); Assert.AreEqual(0, ErrorItems.Count(e => e.Project == ProjectName), $"{TemplateName} error descriptions:{Environment.NewLine}{descriptions}"); }
/// <summary> /// Returns whether results are finished collecting /// </summary> /// <returns>Whether TcUnit results are available</returns> public bool AreResultsAvailable(ErrorItems errorItems) { string line; // First check if we already have results if (AreTestResultsAvailable()) { return(true); } else { for (int i = 1; i <= errorItems.Count; i++) { ErrorItem error = errorItems.Item(i); line = error.Description; if (line.Contains(tcUnitResult_TestSuites)) { string noTestSuites = line.Substring(line.LastIndexOf(tcUnitResult_TestSuites) + tcUnitResult_TestSuites.Length + 1); Int32.TryParse(noTestSuites, out numberOfTestSuites); } if (line.Contains(tcUnitResult_Tests)) { string noTests = line.Substring(line.LastIndexOf(tcUnitResult_Tests) + tcUnitResult_Tests.Length + 1); Int32.TryParse(noTests, out numberOfTests); } if (line.Contains(tcUnitResult_SuccessfulTests)) { string noSuccessfulTests = line.Substring(line.LastIndexOf(tcUnitResult_SuccessfulTests) + tcUnitResult_SuccessfulTests.Length + 1); Int32.TryParse(noSuccessfulTests, out numberOfSuccessfulTests); } if (line.Contains(tcUnitResult_FailedTests)) { string noFailedTests = line.Substring(line.LastIndexOf(tcUnitResult_FailedTests) + tcUnitResult_FailedTests.Length + 1); Int32.TryParse(noFailedTests, out numberOfFailedTests); } } return(AreTestResultsAvailable()); } }
static int Main(string[] args) { bool showHelp = false; Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelKeyPressHandler); log4net.GlobalContext.Properties["LogLocation"] = AppDomain.CurrentDomain.BaseDirectory + "\\logs"; log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config")); OptionSet options = new OptionSet() .Add("v=|TcUnitVerifierPath=", "Path to TcUnit-Verifier TwinCAT solution", v => tcUnitVerifierPath = v) .Add("?|h|help", h => showHelp = h != null); try { options.Parse(args); } catch (OptionException e) { Console.WriteLine(e.Message); Console.WriteLine("Try `TcUnit-Verifier --help' for more information."); return(Constants.RETURN_ERROR); } /* Make sure the user has supplied the path for the Visual Studio solution file. * Also verify that this file exists. */ if (showHelp || tcUnitVerifierPath == null) { DisplayHelp(options); return(Constants.RETURN_ERROR); } if (!File.Exists(tcUnitVerifierPath)) { log.Error("TcUnit-verifier solution " + tcUnitVerifierPath + " does not exist."); return(Constants.RETURN_ERROR); } MessageFilter.Register(); log.Info("Starting TcUnit-Verifier..."); try { vsInstance = new VisualStudioInstance(@tcUnitVerifierPath); vsInstance.Load(); } catch { log.Error("Solution load failed"); // Detailed error messages output by vsInstance.Load() CleanUp(); return(Constants.RETURN_ERROR); } if (vsInstance.GetVisualStudioVersion() == null) { log.Error("Did not find Visual studio version in Visual studio solution file."); CleanUp(); return(Constants.RETURN_ERROR); } log.Info("Cleaning and building TcUnit-Verifier_TwinCAT solution..."); AutomationInterface automationInterface = new AutomationInterface(vsInstance); automationInterface.ITcSysManager.SetTargetNetId("127.0.0.1.1.1"); ITcSmTreeItem plcProject = automationInterface.PlcTreeItem.Child[1]; ITcPlcProject iecProject = (ITcPlcProject)plcProject; log.Info("Generating TcUnit-Verifier_TwinCAT boot project..."); iecProject.GenerateBootProject(true); iecProject.BootProjectAutostart = true; log.Info("Activating TcUnit-Verifier_TwinCAT configuration..."); automationInterface.ITcSysManager.ActivateConfiguration(); log.Info("Restarting TwinCAT..."); automationInterface.ITcSysManager.StartRestartTwinCAT(); // Wait until tests have been running and are finished bool testsFinishedRunningFirstLineFound = false; bool amountOfTestSuitesLineFound = false; bool amountOfTestsLineFound = false; bool amountOfSuccesfulTestsLineFound = false; bool amountOfFailedTestsLineFound = false; bool testsFinishedRunningLastLineFound = false; int numberOfFailedTests = 0; log.Info("Waiting for TcUnit-Verifier_TwinCAT to finish running tests..."); ErrorList errorList = new ErrorList(); while (true) { Thread.Sleep(1000); ErrorItems errorItems = vsInstance.GetErrorItems(); log.Info("... got " + errorItems.Count + " report lines so far."); var newErrors = errorList.AddNew(errorItems); foreach (var error in newErrors.Where(e => e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh)) { if (error.Description.Contains("| ==========TESTS FINISHED RUNNING==========")) { testsFinishedRunningFirstLineFound = true; } if (error.Description.Contains("| TEST SUITES:")) { amountOfTestSuitesLineFound = true; } if (error.Description.Contains("| TESTS:")) { amountOfTestsLineFound = true; } if (error.Description.Contains("| SUCCESSFUL TESTS:")) { amountOfSuccesfulTestsLineFound = true; } if (error.Description.Contains("| FAILED TESTS:")) { amountOfFailedTestsLineFound = true; // Grab the number of failed tests so we can validate it during the assertion phase numberOfFailedTests = Int32.Parse(error.Description.Split().Last()); } if (error.Description.Contains("| ======================================")) { testsFinishedRunningLastLineFound = true; } } if (testsFinishedRunningFirstLineFound && amountOfTestSuitesLineFound && amountOfTestsLineFound && amountOfSuccesfulTestsLineFound && amountOfFailedTestsLineFound && testsFinishedRunningLastLineFound) { break; } } log.Info("Asserting results..."); if (numberOfFailedTests != expectedNumberOfFailedTests) { log.Error("The number of tests that failed (" + numberOfFailedTests + ") does not match expectations (" + expectedNumberOfFailedTests + ")"); } List <ErrorList.Error> errors = new List <ErrorList.Error>(errorList.Where(e => e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh)); /* Insert the test classes here */ new FB_PrimitiveTypes(errors); new FB_AssertTrueFalse(errors); new FB_AssertEveryFailedTestTwice(errors); new FB_CreateFourTestsWithSameName(errors); new FB_ArrayPrimitiveTypes(errors); new FB_CreateDisabledTest(errors); new FB_AnyPrimitiveTypes(errors); new FB_AssertEveryFailedTestTwiceArrayVersion(errors); new FB_AnyToUnionValue(errors); new FB_MultipleAssertWithSameParametersInSameCycleWithSameTest(errors); new FB_MultipleAssertWithSameParametersInDifferentCyclesButWithDifferentTests(errors); new FB_MultipleAssertWithSameParametersInDifferentCyclesAndInSameTest(errors); new FB_SkipAssertionsWhenFinished(errors); new FB_AdjustAssertFailureMessageToMax252CharLengthTest(errors); new FB_CheckIfSpecificTestIsFinished(errors); new FB_TestFinishedNamed(errors); log.Info("Done."); CleanUp(); return(Constants.RETURN_SUCCESSFULL); }
public FB_CreateFourTestsWithSameName(ErrorItems errorItems, string testFunctionBlockInstance) : base(errorItems, testFunctionBlockInstance) { TestOne(); }
public FB_MultipleAssertWithSameParametersInDifferentCyclesAndInSameTest(ErrorItems errorItems, string testFunctionBlockInstance) : base(errorItems, testFunctionBlockInstance) { Assert_SeveralTimes(); }
static void Main(string[] args) { bool showHelp = false; bool enableDebugLoggingLevel = false; Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelKeyPressHandler); log4net.GlobalContext.Properties["LogLocation"] = AppDomain.CurrentDomain.BaseDirectory + "\\logs"; log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config")); OptionSet options = new OptionSet() .Add("v=|VisualStudioSolutionFilePath=", "The full path to the TwinCAT project (sln-file)", v => VisualStudioSolutionFilePath = v) .Add("t=|TcUnitTaskName=", "[OPTIONAL] The name of the task running TcUnit defined under \"Tasks\"", t => TcUnitTaskName = t) .Add("a=|AmsNetId=", "[OPTIONAL] The AMS NetId of the device of where the project and TcUnit should run", a => AmsNetId = a) .Add("w=|TcVersion=", "[OPTIONAL] The TwinCAT version to be used to load the TwinCAT project", w => ForceToThisTwinCATVersion = w) .Add("u=|Timeout=", "[OPTIONAL] Timeout the process with an error after X minutes", u => Timeout = u) .Add("d|debug", "[OPTIONAL] Increase debug message verbosity", d => enableDebugLoggingLevel = d != null) .Add("?|h|help", h => showHelp = h != null); try { options.Parse(args); } catch (OptionException e) { Console.WriteLine(e.Message); Console.WriteLine("Try `TcUnit-Runner --help' for more information."); Environment.Exit(Constants.RETURN_ARGUMENT_ERROR); } if (showHelp) { DisplayHelp(options); Environment.Exit(Constants.RETURN_SUCCESSFULL); } /* Set logging level. * This is handled by changing the log4net.config file on the fly. * The following levels are defined in order of increasing priority: * - ALL * - DEBUG * - INFO * - WARN * - ERROR * - FATAL * - OFF */ XmlDocument doc = new XmlDocument(); doc.Load(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlNode root = doc.DocumentElement; XmlNode subNode1 = root.SelectSingleNode("root"); XmlNode nodeForModify = subNode1.SelectSingleNode("level"); if (enableDebugLoggingLevel) { nodeForModify.Attributes[0].Value = "DEBUG"; } else { nodeForModify.Attributes[0].Value = "INFO"; } doc.Save(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); System.Threading.Thread.Sleep(500); // A tiny sleep just to make sure that log4net manages to detect the change in the file /* Make sure the user has supplied the path for the Visual Studio solution file. * Also verify that this file exists. */ if (VisualStudioSolutionFilePath == null) { log.Error("Visual studio solution path not provided!"); Environment.Exit(Constants.RETURN_VISUAL_STUDIO_SOLUTION_PATH_NOT_PROVIDED); } if (!File.Exists(VisualStudioSolutionFilePath)) { log.Error("Visual studio solution " + VisualStudioSolutionFilePath + " does not exist!"); Environment.Exit(Constants.RETURN_VISUAL_STUDIO_SOLUTION_PATH_NOT_FOUND); } LogBasicInfo(); /* Start a timeout for the process(es) if the user asked for it */ if (Timeout != null) { log.Info("Timeout enabled - process(es) timesout after " + Timeout + " minute(s)"); System.Timers.Timer timeout = new System.Timers.Timer(Int32.Parse(Timeout) * 1000 * 60); timeout.Elapsed += KillProcess; timeout.AutoReset = false; timeout.Start(); } MessageFilter.Register(); TwinCATProjectFilePath = TcFileUtilities.FindTwinCATProjectFile(VisualStudioSolutionFilePath); if (String.IsNullOrEmpty(TwinCATProjectFilePath)) { log.Error("Did not find TwinCAT project file in solution. Is this a TwinCAT project?"); Environment.Exit(Constants.RETURN_TWINCAT_PROJECT_FILE_NOT_FOUND); } if (!File.Exists(TwinCATProjectFilePath)) { log.Error("TwinCAT project file " + TwinCATProjectFilePath + " does not exist!"); Environment.Exit(Constants.RETURN_TWINCAT_PROJECT_FILE_NOT_FOUND); } string tcVersion = TcFileUtilities.GetTcVersion(TwinCATProjectFilePath); if (String.IsNullOrEmpty(tcVersion)) { log.Error("Did not find TwinCAT version in TwinCAT project file path"); Environment.Exit(Constants.RETURN_TWINCAT_VERSION_NOT_FOUND); } try { vsInstance = new VisualStudioInstance(@VisualStudioSolutionFilePath, tcVersion, ForceToThisTwinCATVersion); bool isTcVersionPinned = XmlUtilities.IsTwinCATProjectPinned(TwinCATProjectFilePath); log.Info("Version is pinned: " + isTcVersionPinned); vsInstance.Load(isTcVersionPinned); } catch { log.Error("Error loading VS DTE. Is the correct version of Visual Studio and TwinCAT installed? Is the TcUnit-Runner running with administrator privileges?"); CleanUpAndExitApplication(Constants.RETURN_ERROR_LOADING_VISUAL_STUDIO_DTE); } try { vsInstance.LoadSolution(); } catch { log.Error("Error loading the solution. Try to open it manually and make sure it's possible to open and that all dependencies are working"); CleanUpAndExitApplication(Constants.RETURN_ERROR_LOADING_VISUAL_STUDIO_SOLUTION); } if (vsInstance.GetVisualStudioVersion() == null) { log.Error("Did not find Visual Studio version in Visual Studio solution file"); CleanUpAndExitApplication(Constants.RETURN_ERROR_FINDING_VISUAL_STUDIO_SOLUTION_VERSION); } AutomationInterface automationInterface = new AutomationInterface(vsInstance.GetProject()); if (automationInterface.PlcTreeItem.ChildCount <= 0) { log.Error("No PLC-project exists in TwinCAT project"); CleanUpAndExitApplication(Constants.RETURN_NO_PLC_PROJECT_IN_TWINCAT_PROJECT); } ITcSmTreeItem realTimeTasksTreeItem = automationInterface.RealTimeTasksTreeItem; /* Task name provided */ if (!String.IsNullOrEmpty(TcUnitTaskName)) { log.Info("Setting task '" + TcUnitTaskName + "' enable and autostart, and all other tasks (if existing) to disable and non-autostart"); bool foundTcUnitTaskName = false; /* Find all tasks, and check whether the user provided TcUnit task is amongst them. * Also update the task object (Update <Disabled> and <Autostart>-tag) */ foreach (ITcSmTreeItem child in realTimeTasksTreeItem) { ITcSmTreeItem testTreeItem = realTimeTasksTreeItem.LookupChild(child.Name); string xmlString = testTreeItem.ProduceXml(); string newXmlString = ""; try { if (TcUnitTaskName.Equals(XmlUtilities.GetItemNameFromRealTimeTaskXML(xmlString))) { foundTcUnitTaskName = true; newXmlString = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, false, true); } else { newXmlString = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, true, false); } testTreeItem.ConsumeXml(newXmlString); System.Threading.Thread.Sleep(3000); } catch { log.Error("Could not parse real time task XML data"); CleanUpAndExitApplication(Constants.RETURN_NOT_POSSIBLE_TO_PARSE_REAL_TIME_TASK_XML_DATA); } } if (!foundTcUnitTaskName) { log.Error("Could not find task '" + TcUnitTaskName + "' in TwinCAT project"); CleanUpAndExitApplication(Constants.RETURN_FAILED_FINDING_DEFINED_UNIT_TEST_TASK_IN_TWINCAT_PROJECT); } } /* No task name provided */ else { log.Info("No task name provided. Assuming only one task exists"); /* Check that only one task exists */ if (realTimeTasksTreeItem.ChildCount.Equals(1)) { // Get task name ITcSmTreeItem child = realTimeTasksTreeItem.get_Child(1); ITcSmTreeItem testTreeItem = realTimeTasksTreeItem.LookupChild(child.Name); string xmlString = testTreeItem.ProduceXml(); TcUnitTaskName = XmlUtilities.GetItemNameFromRealTimeTaskXML(xmlString); log.Info("Found task with name '" + TcUnitTaskName + "'"); string newXmlString = ""; newXmlString = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, false, true); testTreeItem.ConsumeXml(newXmlString); System.Threading.Thread.Sleep(3000); } /* Less ore more than one task, which is an error */ else { log.Error("The number of tasks is not equal to 1 (one). Found " + realTimeTasksTreeItem.ChildCount.ToString() + " number of tasks. Please provide which task is the TcUnit task"); CleanUpAndExitApplication(Constants.RETURN_TASK_COUNT_NOT_EQUAL_TO_ONE); } } /* Build the solution and collect any eventual errors. Make sure to * filter out everything that is an error */ vsInstance.CleanSolution(); vsInstance.BuildSolution(); ErrorItems errorsBuild = vsInstance.GetErrorItems(); int tcBuildWarnings = 0; int tcBuildError = 0; for (int i = 1; i <= errorsBuild.Count; i++) { ErrorItem item = errorsBuild.Item(i); if ((item.ErrorLevel != vsBuildErrorLevel.vsBuildErrorLevelLow)) { if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelMedium) { tcBuildWarnings++; } else if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh) { tcBuildError++; log.Error("Description: " + item.Description); log.Error("ErrorLevel: " + item.ErrorLevel); log.Error("Filename: " + item.FileName); } } } /* If we don't have any errors, activate the configuration and * start/restart TwinCAT */ if (tcBuildError.Equals(0)) { /* Check whether the user has provided an AMS NetId. If so, use it. Otherwise use * the local AMS NetId */ if (String.IsNullOrEmpty(AmsNetId)) { AmsNetId = Constants.LOCAL_AMS_NET_ID; } log.Info("Setting target NetId to '" + AmsNetId + "'"); automationInterface.ITcSysManager.SetTargetNetId(AmsNetId); log.Info("Enabling boot project and setting BootProjectAutostart on " + automationInterface.ITcSysManager.GetTargetNetId()); for (int i = 1; i <= automationInterface.PlcTreeItem.ChildCount; i++) { ITcSmTreeItem plcProject = automationInterface.PlcTreeItem.Child[i]; ITcPlcProject iecProject = (ITcPlcProject)plcProject; iecProject.BootProjectAutostart = true; /* add the port that is used for this PLC to the AmsPorts list that * is later used to monitory the AdsState */ string xmlString = plcProject.ProduceXml(); AmsPorts.Add(XmlUtilities.AmsPort(xmlString)); } System.Threading.Thread.Sleep(1000); automationInterface.ActivateConfiguration(); // Wait System.Threading.Thread.Sleep(10000); /* Clean the solution. This is the only way to clean the error list which needs to be * clean prior to starting the TwinCAT runtime */ vsInstance.CleanSolution(); // Wait System.Threading.Thread.Sleep(10000); automationInterface.StartRestartTwinCAT(); } else { log.Error("Build errors in project"); CleanUpAndExitApplication(Constants.RETURN_BUILD_ERROR); } /* Establish a connection to the ADS router */ TcAdsClient tcAdsClient = new TcAdsClient(); /* Run TcUnit until the results have been returned */ TcUnitResultCollector tcUnitResultCollector = new TcUnitResultCollector(); ErrorList errorList = new ErrorList(); log.Info("Waiting for results from TcUnit..."); ErrorItems errorItems; while (true) { System.Threading.Thread.Sleep(10000); /* Monitor the AdsState for each PLC that is used in the * solution. If we can't connect to the Ads Router, we just * carry on. */ try { foreach (int amsPort in AmsPorts) { tcAdsClient.Connect(AmsNetId, amsPort); AdsState adsState = tcAdsClient.ReadState().AdsState; if (adsState != AdsState.Run) { log.Error("Invalid AdsState " + adsState + "<>" + AdsState.Run + ". This could indicate a PLC Exception, terminating ..."); Environment.Exit(Constants.RETURN_INVALID_ADSSTATE); } } } catch (Exception ex) { } finally { tcAdsClient.Disconnect(); } errorItems = vsInstance.GetErrorItems(); var newErrors = errorList.AddNew(errorItems); if (log.IsDebugEnabled) { foreach (var error in newErrors) { log.Debug(error.ErrorLevel + ": " + error.Description); } } log.Info("... got " + errorItems.Count + " report lines so far."); if (tcUnitResultCollector.AreResultsAvailable(errorItems)) { log.Info("All results from TcUnit obtained"); /* The last test suite result can be returned after that we have received the test results, wait a few seconds * and fetch again */ System.Threading.Thread.Sleep(10000); break; } } List <ErrorList.Error> errors = new List <ErrorList.Error>(errorList.Where(e => (e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh || e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelLow))); List <ErrorList.Error> errorsSorted = errors.OrderBy(o => o.Description).ToList(); /* Parse all events (from the error list) from Visual Studio and store the results */ TcUnitTestResult testResult = tcUnitResultCollector.ParseResults(errorsSorted, TcUnitTaskName); /* Write xUnit XML report */ if (testResult != null) { // No need to check if file (VisualStudioSolutionFilePath) exists, as this has already been done string VisualStudioSolutionDirectoryPath = Path.GetDirectoryName(VisualStudioSolutionFilePath); string XUnitReportFilePath = VisualStudioSolutionDirectoryPath + "\\" + Constants.XUNIT_RESULT_FILE_NAME; log.Info("Writing xUnit XML file to " + XUnitReportFilePath); // Overwrites all existing content (if existing) XunitXmlCreator.WriteXml(testResult, XUnitReportFilePath); } CleanUpAndExitApplication(Constants.RETURN_SUCCESSFULL); }
public FB_TestFinishedNamed(ErrorItems errorItems, string testFunctionBlockInstance) : base(errorItems, testFunctionBlockInstance) { Test_FinishedNamed(); }