/*public static TestWorkflowRuntime CreateTestWorkflowRuntime(TestActivity testActivity, params TestServiceRuntime[] serviceRuntimes) * { * TestWorkflowRuntimeConfiguration wrc = TestWorkflowRuntimeConfiguration.GenerateDefaultConfiguration(testActivity); * * if (serviceRuntimes != null && serviceRuntimes.Length > 0) * { * foreach (TestServiceRuntime serviceRuntime in serviceRuntimes) * { * ClientOperationUtility.BindClientOperations(testActivity, serviceRuntime.Configuration, wrc.Settings, false); * } * } * * return new TestWorkflowRuntime(testActivity, wrc); * } */ public static TestWorkflowRuntime CreateTestWorkflowRuntime(TestActivity testActivity, WorkflowIdentity definitionIdentity = null, InstanceStore instanceStore = null, PersistableIdleAction idleAction = PersistableIdleAction.None) { TestWorkflowRuntimeConfiguration wrc = new TestWorkflowRuntimeConfiguration(); return(new TestWorkflowRuntime(testActivity, wrc, instanceStore, idleAction)); }
private void RunTestWithWorkflowRuntime(TestActivity activity) { using (TestWorkflowRuntime testWorkflowRuntime = TestRuntime.CreateTestWorkflowRuntime(activity)) { testWorkflowRuntime.OnWorkflowCompleted += new EventHandler <TestWorkflowCompletedEventArgs>(workflowInstance_Completed); testWorkflowRuntime.ExecuteWorkflow(); WorkflowTrackingWatcher watcher = testWorkflowRuntime.GetWatcher(); OrderedTraces orderedExpectedTrace = new OrderedTraces { Steps = { new WorkflowInstanceTrace(testWorkflowRuntime.CurrentWorkflowInstanceId, WorkflowInstanceState.Started), new WorkflowInstanceTrace(testWorkflowRuntime.CurrentWorkflowInstanceId, WorkflowInstanceState.Terminated), new WorkflowInstanceTrace(testWorkflowRuntime.CurrentWorkflowInstanceId, WorkflowInstanceState.Deleted) { Optional = true } } }; ExpectedTrace expectedWorkflowInstacneTrace = new ExpectedTrace(orderedExpectedTrace); Exception exp = new Exception(); testWorkflowRuntime.WaitForTerminated(1, out exp, watcher.ExpectedTraces, expectedWorkflowInstacneTrace); } }
public void InheritedExceptions1() { // exception which is raised Exception exc = new Exception(); // try TestSequence trySeq = new TestSequence(); trySeq.Activities.Add(new TestWriteLine("Try", "Try")); TestThrow <Exception> tt = new TestThrow <Exception>("TestThrow1") { ExceptionExpression = (context => new Exception()) }; trySeq.Activities.Add(tt); // catch TestCatch[] catches = new TestCatch[] { new TestCatch <ArgumentException>() }; // create and run TestActivity act = CreateTryCatchFinally(trySeq, catches, null, WFType.SEQ, true); TestRuntime.RunAndValidateAbortedException(act, exc.GetType(), new Dictionary <string, string> { { "Message", exc.Message } }); }
public static void RunAndValidateUsingWorkflowInvoker(TestActivity testActivity, Dictionary <string, object> inputs, Dictionary <string, object> expectedOutputs, ICollection <object> extensions, TimeSpan invokeTimeout) { using (TestWorkflowRuntime testWorkflowRuntime = new TestWorkflowRuntime(testActivity)) { testWorkflowRuntime.ExecuteWorkflowInvoker(inputs, expectedOutputs, extensions, invokeTimeout); } }
private static void VerifyLocked(TestActivity activity, ExceptionHelpers.MethodDelegate tryCode) { //No excepion is expected. new WorkflowApplication(activity.ProductActivity); tryCode(); new WorkflowApplication(activity.ProductActivity); }
public static void ValidateWorkflow(Guid workflowInstanceId, TestActivity testWorkflowDefinition) { ActualTrace actualTrace = TestTraceManager.Instance.GetInstanceActualTrace(workflowInstanceId); ExpectedTrace expectedTrace = testWorkflowDefinition.GetExpectedTrace(); actualTrace.Validate(testWorkflowDefinition.GetExpectedTrace()); }
public static void ModifyAndValidateException(TestActivity testActivity, Type exceptionType, string errorString) { string originalXaml = XamlTestDriver.Serialize(testActivity.ProductActivity); string modifiedXaml = testActivity.ModifyXamlDelegate(originalXaml); ExceptionHelpers.CheckForException(exceptionType, errorString, () => Deserialize(modifiedXaml)); }
/// <summary> /// Setup a t/c/f statement. /// </summary> /// <param name="tryBody">Try activity.</param> /// <param name="tc">Array of Catches.</param> /// <param name="finallyBody">Finally activity.</param> /// <param name="type">Type of workflow to create.</param> /// <param name="otherActivities">Flag indicating whether extra activities should be added.</param> public static TestActivity CreateTryCatchFinally(TestActivity tryBody, TestCatch[] tc, TestActivity finallyBody, WFType type, bool otherActivities) { // create the try/catch/finally TestTryCatch tcf = new TestTryCatch("TestTcf"); if (tryBody != null) { tcf.Try = tryBody; } if (tc != null) { foreach (TestCatch testCatch in tc) { tcf.Catches.Add(testCatch); } } if (finallyBody != null) { tcf.Finally = finallyBody; } // extra activities to add around activity if otherActivities is true TestWriteLine before = new TestWriteLine("BeforeTry", "BeforeTry"); TestWriteLine after = new TestWriteLine("AfterTry", "AfterTry"); // sequence if (type == WFType.SEQ) { TestSequence seq = new TestSequence("SequenceOfActivitiesContainingTCF"); if (otherActivities) { seq.Activities.Add(before); } seq.Activities.Add(tcf); if (otherActivities) { seq.Activities.Add(after); } return(seq); } // otherwise do flowchart else // type == wfType.FLOW { TestFlowchart flowchart = new TestFlowchart("FlowchartContainingTCF"); if (otherActivities) { flowchart.AddStartLink(before); flowchart.AddLink(before, tcf); flowchart.AddLink(tcf, after); } else { flowchart.AddStartLink(tcf); } return(flowchart); } }
public void Setup() { _amazonSimpleWorkflow = new Mock <IAmazonSimpleWorkflow>(); var domain = new Domain("name", _amazonSimpleWorkflow.Object); _activityHost = new ActivityHost(domain, new[] { typeof(TestActivity) }, t => new TestActivity(ActivityResult)); TestActivity.Reset(); }
private static void RunAndValidateWorkflow(TestActivity testActivity, ExpectedTrace expectedTrace, List <TestConstraintViolation> constraints, ValidationSettings validatorSettings, bool runValidations, WorkflowIdentity definitionIdentity = null) { using (TestWorkflowRuntime testWorkflowRuntime = new TestWorkflowRuntime(testActivity, definitionIdentity)) { testWorkflowRuntime.ExecuteWorkflow(); testWorkflowRuntime.WaitForCompletion(expectedTrace); } }
public static void ValidateWorkflowErrors(TestActivity testActivity, List <TestConstraintViolation> constraints, Type onOpenExceptionType, string onOpenExceptionString, ValidationSettings validatorSettings) { using (TestWorkflowRuntime testWorkflowRuntime = new TestWorkflowRuntime(testActivity)) { ValidateConstraints(testActivity, constraints, validatorSettings); ValidateInstantiationException(testActivity, onOpenExceptionType, onOpenExceptionString); } }
public void IsActivity(string typeOfActivity, string targetType, bool expected) { var activity = new TestActivity() { Type = typeOfActivity }; Assert.Equal(expected, activity.IsTargetActivityType(targetType)); }
private async Task RunTestTask(TestActivity activity, bool overrideSettings, CancellationToken token) { string parameters = $"/Test /Logging /LoggingFilename=\"{Path.GetFileName(logFilePath)}\" /LoggingPath=\"{Path.GetDirectoryName(logFilePath)}\" " + $"/Profiling /ProfilingTime=10 /ShowErrorDialogs=False"; if (overrideSettings) { parameters += " /Skip-User-Settings"; } ProcessStartInfo processStartInfo = new ProcessStartInfo { FileName = runActivity, WindowStyle = ProcessWindowStyle.Normal, WorkingDirectory = Application.StartupPath }; if (!clearedLogs) { using (StreamWriter writer = File.CreateText(summaryFilePath)) await writer.WriteLineAsync("Route, Activity, Passed, Errors, Warnings, Infos, Load Time, FPS").ConfigureAwait(false); using (StreamWriter writer = File.CreateText(logFilePath)) await writer.FlushAsync().ConfigureAwait(false); clearedLogs = true; } long summaryFilePosition = 0L; using (StreamReader reader = File.OpenText(summaryFilePath)) summaryFilePosition = reader.BaseStream.Length; processStartInfo.Arguments = $"{parameters} \"{activity.ActivityFilePath}\""; activity.Passed = await RunProcess(processStartInfo, token).ConfigureAwait(false) == 0; activity.Tested = true; using (StreamReader reader = File.OpenText(summaryFilePath)) { reader.BaseStream.Seek(summaryFilePosition, SeekOrigin.Begin); string line = await reader.ReadLineAsync().ConfigureAwait(false); if (!string.IsNullOrEmpty(line) && reader.EndOfStream) { string[] csv = line.Split(','); activity.Errors = $"{int.Parse(csv[3], CultureInfo.InvariantCulture)}/{int.Parse(csv[4], CultureInfo.InvariantCulture)}/{int.Parse(csv[5], CultureInfo.InvariantCulture)}"; activity.Load = $"{float.Parse(csv[6], CultureInfo.InvariantCulture),6:F1}s"; activity.FPS = $"{float.Parse(csv[7], CultureInfo.InvariantCulture),6:F1}"; } else { await reader.ReadToEndAsync().ConfigureAwait(false); activity.Passed = false; } summaryFilePosition = reader.BaseStream.Position; } }
public ActivityPlaceholderTrace(TestActivity body) { if (body == null) { throw new ArgumentNullException("body"); } _body = body; this.Provider = this; }
private async Task RunTestTask(TestActivity activity, bool overrideSettings, CancellationToken token) { string parameters = $"/Test /Logging /LoggingFilename=\"{Path.GetFileName(logFilePath)}\" /LoggingPath=\"{Path.GetDirectoryName(logFilePath)}\" " + $"/Profiling /ProfilingTime=10 /ShowErrorDialogs=False"; if (overrideSettings) { parameters += " /Skip-User-Settings"; } var processStartInfo = new ProcessStartInfo { FileName = runActivity, WindowStyle = ProcessWindowStyle.Normal, WorkingDirectory = Application.StartupPath }; if (!clearedLogs) { using (var writer = File.CreateText(summaryFilePath)) writer.WriteLine("Route, Activity, Passed, Errors, Warnings, Infos, Loading, FPS"); using (var writer = File.CreateText(logFilePath)) writer.Flush(); clearedLogs = true; } long summaryFilePosition = 0L; using (var reader = File.OpenText(summaryFilePath)) summaryFilePosition = reader.BaseStream.Length; processStartInfo.Arguments = $"{parameters} \"{activity.ActivityFilePath}\""; activity.Passed = await RunProcess(processStartInfo, token) == 0; activity.Tested = true; using (var reader = File.OpenText(summaryFilePath)) { reader.BaseStream.Seek(summaryFilePosition, SeekOrigin.Begin); var line = reader.ReadLine(); if (!String.IsNullOrEmpty(line) && reader.EndOfStream) { var csv = line.Split(','); activity.Errors = String.Format("{0}/{1}/{2}", int.Parse(csv[3]), int.Parse(csv[4]), int.Parse(csv[5])); activity.Load = String.Format("{0,6:F1}s", float.Parse(csv[6])); activity.FPS = String.Format("{0,6:F1}", float.Parse(csv[7])); } else { reader.ReadToEnd(); activity.Passed = false; } summaryFilePosition = reader.BaseStream.Position; } }
public static void RunAndValidateAbortedException(TestActivity activity, Type exceptionType, Dictionary <string, string> exceptionProperties) { using (TestWorkflowRuntime testWorkflowRuntime = new TestWorkflowRuntime(activity)) { testWorkflowRuntime.ExecuteWorkflow(); testWorkflowRuntime.WaitForAborted(out Exception exception, true); ExceptionHelpers.ValidateException(exception, exceptionType, exceptionProperties); } }
public async Task SetsObsoleteCorrelationIdFromHeaderToActivity(string correlationName) { // Arrange Guid obsoleteCorrelation = Guid.NewGuid(); TestHttpContext.Request.Headers.Add(correlationName, obsoleteCorrelation.ToString()); // Act await TestMiddleware.InvokeAsync(TestHttpContext, DummyDelegate); // Assert Assert.AreEqual(obsoleteCorrelation.ToString(), TestActivity.GetBaggageItem("ObsoleteCorrelationId")); }
public void Messaging_BigActivity() { SnLog.Instance = new TestLogger(); //---- Ensure test data var entities = CreateTestEntities(); var groups = SystemStartTests.CreateTestGroups(); var memberships = Tools.CreateInMemoryMembershipTable(groups); var aces = CreateTestAces(); var storage = new DatabaseStorage { Aces = aces, Memberships = memberships, Entities = entities, Messages = new List <Tuple <int, DateTime, byte[]> >() }; //---- Start the system var msgProvider = new TestMessageProvider(); msgProvider.Initialize(); Context.StartTheSystem(new MemoryDataProviderForMessagingTests(storage), msgProvider); context = new Context(TestUser.User1); // small activity var smallActivity = new TestActivity(); smallActivity.Execute(context.Security); var smallActivityId = smallActivity.Id; // large activity var largeActivity = new TestActivity() { Body = new String('*', Configuration.DistributableSecurityActivityMaxSize + 1) }; largeActivity.Execute(context.Security); var largeActivityId = largeActivity.Id; // check the logger var expected = String.Format("Executing unprocessed security activities., " + "Send: TestActivity, Applied: #{0}, " + "Send: BigActivityMessage, LoadMessage: TestActivity#{1}, Applied: #{1}", smallActivityId, largeActivityId); var testLogger = (TestLogger)SnLog.Instance; var actual = string.Join(", ", testLogger.Informations); Assert.AreEqual(expected, actual); }
private void Validate(TestActivity activity, List <string> errors) { List <TestConstraintViolation> constraints = new List <TestConstraintViolation>(); if (errors != null) { foreach (string error in errors) { constraints.Add(new TestConstraintViolation(error, activity.ProductActivity)); } } TestRuntime.ValidateConstraints(activity, constraints, null); }
public void ContentChange(string activtyId, string activityName) { TestActivity testActivity = new TestActivity(activityName, activtyId) { mainWindow = this, Uid = activtyId, ActivityId = activtyId, ActivityName = activityName }; ContentControl.Content = new Frame() { Content = testActivity }; }
public void TryCatchFinallyWithExceptionInFinally() { // Uncaught Exception ArithmeticException exc = new ArithmeticException(); // finally TestThrow <ArithmeticException> tt = new TestThrow <ArithmeticException>("Test Throw") { ExceptionExpression = (context => new ArithmeticException()) }; // Run test TestActivity act = CreateTryCatchFinally(null, null, tt, WFType.SEQ, false); TestRuntime.RunAndValidateAbortedException(act, exc.GetType(), null); }
public static void ValidateInstantiationException(TestActivity testActivity, Type exceptionType, string errorString) { Dictionary <string, string> exception = new Dictionary <string, string>(); exception.Add("Message", errorString); ExceptionHelpers.CheckForException( exceptionType, exception, delegate { WorkflowApplication instance = new WorkflowApplication(testActivity.ProductActivity); instance.Extensions.Add(TestRuntime.TraceListenerExtension); instance.Run(); }, true); }
public void ActivitySearcher_GetSearchResults_WhenToolTitleHasValue_ShouldReturnResult() { var mockResourceCatalog = new Mock <IResourceCatalog>(); var mockResource = new Mock <IResource>(); mockResource.Setup(r => r.ResourceID).Returns(Guid.Empty); mockResource.Setup(r => r.ResourceName).Returns("Test Resource"); mockResource.Setup(r => r.GetResourcePath(It.IsAny <Guid>())).Returns("Folder"); mockResourceCatalog.Setup(res => res.GetResource(It.IsAny <Guid>(), It.IsAny <Guid>())).Returns(mockResource.Object); var searcher = new ActivitySearcher(mockResourceCatalog.Object); var search = new Common.Search.Search { SearchInput = "Set", SearchOptions = new SearchOptions { IsAllSelected = false, IsToolTitleSelected = true } }; var mockResourceActivityCache = new Mock <IResourceActivityCache>(); var cache = new System.Collections.Concurrent.ConcurrentDictionary <Guid, IDev2Activity>(); var startAct = new TestActivity { DisplayName = "Start Tool", NextNodes = new List <IDev2Activity> { new TestActivity { DisplayName = "Set a value" } } }; cache.TryAdd(Guid.Empty, startAct); mockResourceActivityCache.Setup(c => c.Cache).Returns(cache); mockResourceCatalog.Setup(res => res.GetResourceActivityCache(It.IsAny <Guid>())).Returns(mockResourceActivityCache.Object); var searchResults = searcher.GetSearchResults(search); Assert.AreEqual(1, searchResults.Count); var searchResult = searchResults[0]; Assert.AreEqual(Guid.Empty, searchResult.ResourceId); Assert.AreEqual("Set a value", searchResult.Match); Assert.AreEqual("Test Resource", searchResult.Name); Assert.AreEqual("Folder", searchResult.Path); Assert.AreEqual(Common.Interfaces.Search.SearchItemType.ToolTitle, searchResult.Type); }
/// <summary> /// Exception is thrown in try and caught. /// Exception is thrown in try and caught. Catch contains a base of thrown child exception. /// </summary> /// Disabled and failed in desktop //[Fact] public void InheritedExceptions2() { // try TestSequence trySeq = new TestSequence(); trySeq.Activities.Add(new TestWriteLine("Try", "Try")); trySeq.Activities.Add(new TestThrow <ArgumentException>("TestThrow1")); // catch TestCatch[] catches = new TestCatch[] { new TestCatch <Exception>() }; catches[0].HintHandleException = true; // create and run TestActivity act = CreateTryCatchFinally(trySeq, catches, null, WFType.SEQ, true); TestRuntime.RunAndValidateWorkflow(act); }
public void Messaging_MessageSender() { SnLog.Instance = new TestLogger(); //---- Ensure test data var entities = CreateTestEntities(); var groups = SystemStartTests.CreateTestGroups(); var memberships = Tools.CreateInMemoryMembershipTable(groups); var aces = CreateTestAces(); var storage = new DatabaseStorage { Aces = aces, Memberships = memberships, Entities = entities, Messages = new List <Tuple <int, DateTime, byte[]> >() }; //---- Start the system var messageSenderManager = new MessageSenderManager(); var msgProvider = new TestMessageProvider(messageSenderManager); msgProvider.MessageReceived += MsgProvider_MessageReceived; msgProvider.Initialize(); var securitySystem = Context.StartTheSystem(new MemoryDataProviderForMessagingTests(storage), msgProvider); _context = new Context(TestUser.User1, securitySystem); // small activity from me var activity1 = new TestActivity(); activity1.Execute(_context.Security); // small activity from another var activity2 = new TestActivity { Sender = new TestMessageSender { ComputerID = Environment.MachineName, InstanceID = "AnotherAppDomain" } }; activity2.Execute(_context.Security); Assert.AreEqual("true, false", string.Join(", ", msgProvider.ReceiverMessages)); }
public async Task InvokeAsync_NotWrapped_Continues() { // arrange var activity = new TestActivity(); var serviceProvider = new Mock <IServiceProvider>(); DispatchMiddlewareContext context = CreateContext(activity); var middleware = new ServiceProviderActivityMiddleware(serviceProvider.Object); // act await middleware.InvokeAsync(context, () => Task.CompletedTask); // assert TaskActivity actual = context.GetProperty <TaskActivity>(); actual.Should().NotBeNull(); actual.Should().Be(activity); serviceProvider.Verify(m => m.GetService(It.IsAny <Type>()), Times.Never); }
public void CatchBothUnhandledExceptionHandlerAndInCatch() { // try // Throws a handled exception, then a caught exception TestSequence trySeq = new TestSequence("Try") { Activities = { new TestThrow <FormatException>("ThrowFormat") { ExceptionExpression = (context => new FormatException(CustomUtility.CustomMessage)), ExpectedOutcome = Outcome.HandledException(), }, }, ExpectedOutcome = Outcome.Canceled }; // catch // Should not catch anything TestCatch[] catches = new TestCatch[] { new TestCatch <ArgumentException>() { } }; // finally // Just confirm it executed TestWriteLine finalSeq = new TestWriteLine("Final", "Final"); // Run test TestActivity act = CreateTryCatchFinally(trySeq, catches, finalSeq, WFType.SEQ, false); // Run and validate trace using (TestWorkflowRuntime runtime = TestRuntime.CreateTestWorkflowRuntime(act)) { // Add the unhandled handler runtime.WorkflowRuntimeAdapterType = typeof(AddHandleExceptionRuntimeAdapter); runtime.ExecuteWorkflow(); runtime.GetWatcher().WaitForWorkflowCanceled(); } }
// Helper which flips an uncaughtexception to caught public static bool CatchAnException(Type type, TestActivity act) { UncaughtExceptionOutcome ueo = act.ExpectedOutcome as UncaughtExceptionOutcome; //if (ueo != null && type.IsAssignableFrom(ueo.ExceptionType)) //{ // act.ExpectedOutcome = new CaughtExceptionOutcome(ueo.ExceptionType); // return true; //} //else //{ // foreach (TestActivity child in act.GetChildren()) // { // if (CatchAnException(type, child)) // return true; // } //} return(false); }
public void TryCatchFinallyCustomException() { // try TestThrow <CustomException> custromTry = new TestThrow <CustomException>("custom exception") { ExceptionExpression = (context => new CustomException("Invalid department")), ExpectedOutcome = Outcome.CaughtException() }; // catch TestCatch[] catches = new TestCatch[] { new TestCatch <CustomException>() }; // finally TestWriteLine finallyWrite = new TestWriteLine("FinallyCatchingCustomException", "FinallyCatchingCustomException"); // create and run TestActivity act = CreateTryCatchFinally(custromTry, catches, finallyWrite, WFType.SEQ, true); TestRuntime.RunAndValidateWorkflow(act); }
private static void HostWorkflowAsService(TestActivity testActivity, ExpectedTrace expectedTrace, Type abortedExceptionType, Dictionary <string, string> abortedExceptionProperties) { //Log.TraceInternal("Standalone Workflow is being hosted as Service."); //Host it as a service /*using (TestWorkflowServiceRuntime serviceRuntime = CreateTestWorkflowServiceRuntime(testActivity)) * { * serviceRuntime.Configuration.AddWorkflowCreationEndPoint(); * serviceRuntime.StartService(); * * //Log.TraceInternal("Wait 7sec for IIS to catch-up."); * System.Threading.Thread.CurrentThread.Join(TimeSpan.FromSeconds(7)); * * WorkflowCreationClient creationClient = serviceRuntime.CreateWorkflowCreationClient(); * * Guid workflowInstanceId = creationClient.Create(); * * if (abortedExceptionType == null) * { * if (expectedTrace != null) * serviceRuntime.WaitForCompletion(workflowInstanceId, expectedTrace); * else * serviceRuntime.WaitForCompletion(workflowInstanceId, true); * } * else * { * Exception exception; * if (expectedTrace != null) * serviceRuntime.WaitForAborted(workflowInstanceId, out exception, expectedTrace); * else * serviceRuntime.WaitForAborted(workflowInstanceId, out exception, true); * * ExceptionHelpers.ValidateException(exception, abortedExceptionType, abortedExceptionProperties); * } * * creationClient.Close(); * * serviceRuntime.StopService(); * }*/// Should have our WorkflowApplication or WorkflowInvoker implementation }