public void UnorderedNonReentrantGrain() { IUnorderedNonReentrantGrain unonreentrant = GrainClient.GrainFactory.GetGrain <IUnorderedNonReentrantGrain>(GetRandomGrainId()); unonreentrant.SetSelf(unonreentrant).Wait(); bool timeout = false; bool deadlock = false; try { timeout = !unonreentrant.Two().Wait(2000); } catch (Exception exc) { Exception baseExc = exc.GetBaseException(); if (baseExc.GetType().Equals(typeof(DeadlockException))) { deadlock = true; } else { Assert.Fail("Unexpected exception {0}: {1}", exc.Message, exc.StackTrace); } } if (this.HostedCluster.Primary.Silo.GlobalConfig.PerformDeadlockDetection) { Assert.IsTrue(deadlock, "Non-reentrant grain should deadlock"); } else { Assert.IsTrue(timeout, "Non-reentrant grain should timeout"); } logger.Info("Reentrancy UnorderedNonReentrantGrain Test finished OK."); }
public async Task SiloUngracefulShutdown_OutstandingRequestsBreak() { var grain = HostedCluster.GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid()); var instanceId = await grain.GetRuntimeInstanceId(); var target = HostedCluster.GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid()); var targetInstanceId = await target.GetRuntimeInstanceId(); Assert.AreNotEqual(instanceId, targetInstanceId, "Activations must be placed on different silos"); var promise = instanceId.Contains(HostedCluster.Primary.Endpoint.ToString()) ? grain.CallOtherLongRunningTask(target, true, TimeSpan.FromSeconds(7)) : target.CallOtherLongRunningTask(grain, true, TimeSpan.FromSeconds(7)); await Task.Delay(500); HostedCluster.KillSilo(HostedCluster.SecondarySilos[0]); try { await promise; Assert.Fail("The broken promise exception was not thrown"); } catch (Exception ex) { Assert.AreEqual(typeof(SiloUnavailableException), ex.GetBaseException().GetType()); } }
public void SetNextLine(VisualStudioApp app, DotNotWaitOnNormalExit optionSetter) { var project = OpenDebuggerProjectAndBreak(app, "SetNextLine.py", 7); var doc = app.Dte.Documents.Item("SetNextLine.py"); ((TextSelection)doc.Selection).GotoLine(8); ((TextSelection)doc.Selection).EndOfLine(false); var curLine = ((TextSelection)doc.Selection).CurrentLine; app.Dte.Debugger.SetNextStatement(); app.Dte.Debugger.StepOver(true); WaitForMode(app, dbgDebugMode.dbgBreakMode); var curFrame = app.Dte.Debugger.CurrentStackFrame; var local = curFrame.Locals.Item("y"); Assert.AreEqual("100", local.Value); try { curFrame.Locals.Item("x"); Assert.Fail("Expected exception, x should not be defined"); } catch { } app.Dte.Debugger.TerminateAll(); WaitForMode(app, dbgDebugMode.dbgDesignMode); }
private async Task Operation(int opNumber) { if (operationsInProgress > 0) { Assert.Fail("1: Operation {0} found {1} operationsInProgress.", opNumber, operationsInProgress); } operationsInProgress++; var delay = random.NextTimeSpan(TimeSpan.FromSeconds(2)); logger.Info("Task {0} Staring", opNumber); await Task.Delay(delay); if (operationsInProgress != 1) { Assert.Fail("2: Operation {0} found {1} operationsInProgress.", opNumber, operationsInProgress); } logger.Info("Task {0} after first delay", opNumber); await Task.Delay(delay); if (operationsInProgress != 1) { Assert.Fail("3: Operation {0} found {1} operationsInProgress.", opNumber, operationsInProgress); } operationsInProgress--; logger.Info("Task {0} Done", opNumber); }
public void Async_AsyncExecutorWithRetriesTest_4() { int counter = 0; int lastIteration = 0; Func <int, Task <int> > myFunc = ((int funcCounter) => { lastIteration = funcCounter; Assert.AreEqual(counter, funcCounter); output.WriteLine("Running for {0} time.", counter); return(Task.FromResult(++counter)); }); Func <Exception, int, bool> errorFilter = ((Exception exc, int i) => { Assert.AreEqual(lastIteration, i); Assert.Fail("Should not be called"); return(true); }); int maxRetries = 5; Task <int> promise = AsyncExecutorWithRetries.ExecuteWithRetries( myFunc, maxRetries, errorFilter, default(TimeSpan), new FixedBackoff(TimeSpan.FromSeconds(1))); int value = promise.Result; output.WriteLine("Value={0} Counter={1} ExpectedRetries={2}", value, counter, 0); Assert.AreEqual(counter, value, "Counter == Returned value"); Assert.AreEqual(counter, 1, "Counter == Returned value"); }
public void FailSideCastAfterContinueWith() { Xunit.Assert.Throws <InvalidCastException>(() => { // GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference try { IGeneratorTestDerivedGrain1 grain = GrainClient.GrainFactory.GetGrain <IGeneratorTestDerivedGrain1>(GetRandomGrainId()); IGeneratorTestDerivedGrain2 cast = null; Task <bool> av = grain.StringIsNullOrEmpty(); Task <bool> av2 = av.ContinueWith((Task <bool> t) => Assert.IsTrue(t.Result)).ContinueWith((_AppDomain) => { cast = grain.AsReference <IGeneratorTestDerivedGrain2>(); }).ContinueWith((_) => cast.StringConcat("a", "b", "c")).ContinueWith((_) => cast.StringIsNullOrEmpty().Result); Assert.IsFalse(av2.Result); } catch (AggregateException ae) { Exception ex = ae.InnerException; while (ex is AggregateException) { ex = ex.InnerException; } throw ex; } Assert.Fail("Exception should have been raised"); }); }
public async Task Constructor_Bad_Await() { try { int id = random.Next(); IBadConstructorTestGrain grain = GrainClient.GrainFactory.GetGrain <IBadConstructorTestGrain>(id); await grain.DoSomething(); Assert.Fail("Expected ThrowSomething call to fail as unable to Activate grain"); } catch (TimeoutException te) { Console.WriteLine("Received timeout: " + te); throw; // Fail test } catch (Exception exc) { Console.WriteLine("Received exception: " + exc); Exception e = exc.GetBaseException(); Console.WriteLine("Nested exception type: " + e.GetType().FullName); Console.WriteLine("Nested exception message: " + e.Message); Assert.IsInstanceOfType(e, typeof(Exception), "Did not get expected exception type returned: " + e); Assert.IsNotInstanceOfType(e, typeof(InvalidOperationException), "Did not get expected exception type returned: " + e); Assert.IsTrue(e.Message.Contains("Constructor"), "Did not get expected exception message returned: " + e.Message); } }
// check that premature wait finishes on time but does not throw with false and later wait throws. public void ErrorHandlingTimedMethodWithError() { var grainFullName = typeof(ErrorGrain).FullName; IErrorGrain grain = GrainClient.GrainFactory.GetGrain <IErrorGrain>(GetRandomGrainId(), grainFullName); Task promise = grain.LongMethodWithError(2000); // there is a race in the test here. If run in debugger, the invocation can actually finish OK Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Assert.IsFalse(promise.Wait(1000), "The task shouldn't have completed yet."); stopwatch.Stop(); Assert.IsTrue(stopwatch.ElapsedMilliseconds >= 900, "Waited less than 900ms"); // check that we waited at least 0.9 second Assert.IsTrue(stopwatch.ElapsedMilliseconds <= 1100, "Waited longer than 1100ms"); try { promise.Wait(); Assert.Fail("Should have thrown"); } catch (Exception) { } Assert.IsTrue(promise.Status == TaskStatus.Faulted); }
public async Task ActivationSched_WhenAny_Timeout() { TaskScheduler scheduler = masterScheduler.GetWorkItemGroup(context).TaskRunner; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource <bool>(); Task <int> task1 = null; Task <int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task <int> .Factory.StartNew(() => { output.WriteLine("Task-1 Started"); Assert.AreEqual(scheduler, TaskScheduler.Current, "TaskScheduler.Current=" + TaskScheduler.Current); pause1.WaitOne(); output.WriteLine("Task-1 Done"); return(1); }); task2 = Task <int> .Factory.StartNew(() => { output.WriteLine("Task-2 Started"); Assert.AreEqual(scheduler, TaskScheduler.Current, "TaskScheduler.Current=" + TaskScheduler.Current); pause2.WaitOne(); output.WriteLine("Task-2 Done"); return(2); }); join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2))); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.Fail("Result did not arrive before timeout " + timeoutLimit); } Assert.IsNotNull(join, "Joined promise assigned"); await join; Assert.IsTrue(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status); Assert.IsFalse(task1.IsFaulted, "Task-1 Faulted " + task1.Exception); Assert.IsFalse(task1.IsCompleted, "Task-1 Status " + task1.Status); Assert.IsFalse(task2.IsFaulted, "Task-2 Faulted " + task2.Exception); Assert.IsFalse(task2.IsCompleted, "Task-2 Status " + task2.Status); pause1.Set(); task1.Ignore(); pause2.Set(); task2.Ignore(); }
public void FrameViewColumnCoercion() { // Create nullable double and integer columns. FrameTable table = new FrameTable(); table.AddColumn <double?>("one"); table.AddColumn <int>("two"); table.AddRow(1.1, 2); table.AddRow(null, 3); // Coerce the nullable double into a non-nullable double // Should work when value is non-null, and fail with value is null IReadOnlyList <double> one = table["one"].As <double>(); Assert.IsTrue(one[0] == 1.1); try { double v = one[1]; Assert.Fail(); } catch (Exception) { } // Coerce the integer to a double. IReadOnlyList <double> two = table.Columns[1].As <double>(); Assert.IsTrue(two[0] == 2.0); }
void ObserverTest_SimpleNotification_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_SimpleNotification_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); if (a == 3 && b == 0) { callbacksRecieved[0] = true; } else if (a == 3 && b == 2) { callbacksRecieved[1] = true; } else { throw new ArgumentOutOfRangeException("Unexpected callback with values: a=" + a + ",b=" + b); } if (callbackCounter == 1) { // Allow for callbacks occurring in any order Assert.IsTrue(callbacksRecieved[0] || callbacksRecieved[1], "Received one callback ok"); } else if (callbackCounter == 2) { Assert.IsTrue(callbacksRecieved[0] && callbacksRecieved[1], "Received two callbacks ok"); result.Done = true; } else { Assert.Fail("Callback has been called more times than was expected."); } }
public async Task ObserverTest_Unsubscribe() { TestInitialize(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(null, null); ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference <ISimpleGrainObserver>(observer1); try { await grain.Unsubscribe(reference); await GrainFactory.DeleteObjectReference <ISimpleGrainObserver>(reference); } catch (TimeoutException) { throw; } catch (Exception exc) { Exception baseException = exc.GetBaseException(); if (!(baseException is OrleansException)) { Assert.Fail("Unexpected exception type {0}", baseException); } } }
public void IsProcessRunning_ProcessNotRunning_ReportFalse() { // Shut down any instances of calc. Process[] calcProcess = Process.GetProcessesByName("calc"); foreach (Process orleansHostProcess in calcProcess) { orleansHostProcess.Kill(); } // Run the script; the result should be "False". Collection <PSObject> results = RunPowerShellCommand(".\\IsProcessRunning.ps1", "calc", "localHost"); if (results.Count != 0) { // Check the results for an error or exception. CheckResultsForErrors(results); StringBuilder resultsBuilder = new StringBuilder(); foreach (PSObject result in results) { resultsBuilder.AppendLine(result.ToString()); } Assert.Fail("IsProcessRunning.ps1 script returned information when it should have return nothing: {0}", resultsBuilder); } }
public void TestOutboundOrderInsufficientStock() { onSetUp(); stockRepository.AddStock(WAREHOUSE_ID, new List <StockAlteration>() { new StockAlteration(productId, 10) }); var outboundOrder = new OutboundOrderRequestModel() { WarehouseId = WAREHOUSE_ID, OrderLines = new List <OrderLine>() { new OrderLine() { gtin = GTIN, quantity = 11 } } }; try { outboundOrderController.Post(outboundOrder); Assert.Fail("Expected exception to be thrown."); } catch (InsufficientStockException e) { Assert.IsTrue(e.Message.Contains(GTIN)); } }
public static Exception Throws <T>(Action action) where T : Exception { Exception targetException = null; try { action(); } catch (T ex) { // Test pass return(ex); } #if PORTABLE catch (System.Reflection.TargetInvocationException ex) { var inner = ex.InnerException; if (inner is T) { return(inner); } else { FrameworkAssert.Fail(String.Format("Wrong exception type thrown. Expected {0}, got {1}.", typeof(T), inner.GetType())); } } #endif catch (Exception ex) { FrameworkAssert.Fail(String.Format("Wrong exception type thrown. Expected {0}, got {1}.", typeof(T), ex.GetType())); } FrameworkAssert.Fail(String.Format("No Expected {0} was thrown", typeof(T).FullName)); throw new Exception(); }
public void TestOutboundOrderBadGtin() { onSetUp(); var badGtin = GTIN + "XYZ"; var outboundOrder = new OutboundOrderRequestModel() { WarehouseId = WAREHOUSE_ID, OrderLines = new List <OrderLine>() { new OrderLine() { gtin = GTIN, quantity = 1 }, new OrderLine() { gtin = badGtin, quantity = 1 } } }; try { outboundOrderController.Post(outboundOrder); Assert.Fail("Expected exception to be thrown."); } catch (NoSuchEntityException e) { Assert.IsTrue(e.Message.Contains(badGtin)); } }
public void EchoGrain_Timeout_Wait() { grain = GrainClient.GrainFactory.GetGrain <IEchoTaskGrain>(Guid.NewGuid()); TimeSpan delay30 = TimeSpan.FromSeconds(30); // grain call timeout (set in config) TimeSpan delay45 = TimeSpan.FromSeconds(45); TimeSpan delay60 = TimeSpan.FromSeconds(60); Stopwatch sw = new Stopwatch(); sw.Start(); Task <int> promise = grain.BlockingCallTimeoutAsync(delay60); bool ok = promise.ContinueWith(t => { if (!t.IsFaulted) { Assert.Fail("BlockingCallTimeout should not have completed successfully"); } Exception exc = t.Exception; while (exc is AggregateException) { exc = exc.InnerException; } Assert.IsInstanceOfType(exc, typeof(TimeoutException), "Received exception type: {0}", exc); }).Wait(delay45); sw.Stop(); Assert.IsTrue(ok, "Wait should not have timed-out. The grain call should have time out."); Assert.IsTrue(TimeIsLonger(sw.Elapsed, delay30), "Elapsted time out of range: {0}", sw.Elapsed); Assert.IsTrue(TimeIsShorter(sw.Elapsed, delay60), "Elapsted time out of range: {0}", sw.Elapsed); }
// check that grain that throws an error breaks its promise and later Wait and GetValue on it will throw public void ErrorHandlingGrainError1() { var grainFullName = typeof(ErrorGrain).FullName; IErrorGrain grain = GrainClient.GrainFactory.GetGrain <IErrorGrain>(GetRandomGrainId(), grainFullName); Task <int> intPromise = grain.GetAxBError(); try { intPromise.Wait(); Assert.Fail("Should have thrown"); } catch (Exception) { Assert.IsTrue(intPromise.Status == TaskStatus.Faulted); } try { intPromise.Wait(); Assert.Fail("Should have thrown"); } catch (Exception exc2) { Assert.IsTrue(intPromise.Status == TaskStatus.Faulted); Assert.AreEqual((new Exception("GetAxBError-Exception")).Message, exc2.GetBaseException().Message); } Assert.IsTrue(intPromise.Status == TaskStatus.Faulted); }
public async Task EchoGrain_Timeout_Result() { grain = GrainClient.GrainFactory.GetGrain <IEchoTaskGrain>(Guid.NewGuid()); TimeSpan delay30 = TimeSpan.FromSeconds(30); TimeSpan delay60 = TimeSpan.FromSeconds(60); Stopwatch sw = new Stopwatch(); sw.Start(); try { int res = await grain.BlockingCallTimeoutAsync(delay60); Assert.Fail("BlockingCallTimeout should not have completed successfully, but returned " + res); } catch (Exception exc) { while (exc is AggregateException) { exc = exc.InnerException; } Assert.IsInstanceOfType(exc, typeof(TimeoutException), "Received exception type: {0}", exc); } sw.Stop(); Assert.IsTrue(TimeIsLonger(sw.Elapsed, delay30), "Elapsted time out of range: {0}", sw.Elapsed); Assert.IsTrue(TimeIsShorter(sw.Elapsed, delay60), "Elapsted time out of range: {0}", sw.Elapsed); }
private static Task CancellationTokenTest(RelationalStorageForTesting sut, TimeSpan timeoutLimit) { Skip.If(sut == null, "Database was not initialized correctly"); using (var tokenSource = new CancellationTokenSource(timeoutLimit)) { try { //Here one second is added to the task timeout limit in order to account for the delays. //The delays are mainly in the underlying ADO.NET libraries and database. var task = sut.Storage.ReadAsync <int>(sut.CancellationTestQuery, tokenSource.Token); if (!task.Wait(timeoutLimit.Add(TimeSpan.FromSeconds(1)))) { Assert.Fail(string.Format("Timeout limit {0} ms exceeded.", timeoutLimit.TotalMilliseconds)); } } catch (Exception ex) { //There can be a DbException due to the operation being forcefully cancelled... //... Unless this is a test for a provider which does not support for cancellation. if (sut.Storage.SupportsCommandCancellation()) { //If the operation is cancelled already before database calls, a OperationCancelledException //will be thrown in any case. Assert.IsTrue(ex is DbException || ex is OperationCanceledException, "Unexcepted exception: {0}", ex); } else { Assert.IsTrue(ex is OperationCanceledException, "Unexcepted exception: {0}", ex); } } } return(TaskDone.Done); }
public void AgentRestart() { TestAgent t = new TestAgent(output); t.Start(); Assert.AreEqual <ThreadState>(ThreadState.Running, t.State, "Agent state is wrong after initial start"); Thread.Sleep(100); t.Stop(); Assert.AreEqual <ThreadState>(ThreadState.Stopped, t.State, "Agent state is wrong after initial stop"); Thread.Sleep(100); try { t.Start(); } catch (Exception ex) { Assert.Fail("Exception while restarting agent: " + ex.ToString()); throw; } Assert.AreEqual <ThreadState>(ThreadState.Running, t.State, "Agent state is wrong after restart"); Thread.Sleep(100); t.Stop(); Assert.AreEqual <ThreadState>(ThreadState.Stopped, t.State, "Agent state is wrong after final stop"); Thread.Sleep(100); }
public async Task AzureTableDataManager_CreateTableEntryAsync() { var data = GenerateNewData(); await manager.CreateTableEntryAsync(data); try { var data2 = data.Clone(); data2.StringData = "NewData"; await manager.CreateTableEntryAsync(data2); Assert.Fail("Should have thrown StorageException."); } catch (StorageException exc) { Assert.AreEqual((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode, "Creating an already existing entry."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.Conflict, httpStatusCode); Assert.AreEqual("EntityAlreadyExists", restStatus); } var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey); Assert.AreEqual(data.StringData, tuple.Item1.StringData); }
public void AssertContainsExactly <T>(HashSet <T> set, params T[] values) { if (set.ContainsExactly(values)) { return; } Assert.Fail(String.Format("Expected {0}, got {1}", MakeText(values), MakeText(set))); }
public void AssertDoesntContain <T>(IEnumerable <T> source, T value) { foreach (var v in source) { if (v.Equals(value)) { Assert.Fail(String.Format("{0} does not contain {1}", MakeText(source), value)); } } }
public async Task AzureTableDataManager_InsertTwoTableEntriesConditionallyAsync() { var data1 = GenerateNewData(); var data2 = GenerateNewData(); try { await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, AzureStorageUtils.ANY_ETAG); } catch (StorageException exc) { Assert.AreEqual((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode, "Upadte item 2 before created it."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.NotFound, httpStatusCode); Assert.AreEqual(StorageErrorCodeStrings.ResourceNotFound, restStatus); } string etag = await manager.CreateTableEntryAsync(data2.Clone()); var tuple = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag); try { await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), tuple.Item2); Assert.Fail("Should have thrown StorageException."); } catch (StorageException exc) { Assert.AreEqual((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode, "Inserting an already existing item 1."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.Conflict, httpStatusCode); Assert.AreEqual("EntityAlreadyExists", restStatus); } try { await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), AzureStorageUtils.ANY_ETAG); Assert.Fail("Should have thrown StorageException."); } catch (StorageException exc) { Assert.AreEqual((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode, "Inserting an already existing item 1 AND wring eTag"); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.Conflict, httpStatusCode); Assert.AreEqual("EntityAlreadyExists", restStatus); }; }
public void Timeout_LongMethod() { bool finished = false; var grainName = typeof(ErrorGrain).FullName; IErrorGrain grain = GrainClient.GrainFactory.GetGrain <IErrorGrain>(GetRandomGrainId(), grainName); TimeSpan timeout = TimeSpan.FromMilliseconds(1000); RuntimeClient.Current.SetResponseTimeout(timeout); Task promise = grain.LongMethod((int)timeout.Multiply(4).TotalMilliseconds); //promise = grain.LongMethodWithError(2000); // there is a race in the test here. If run in debugger, the invocation can actually finish OK Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); try { finished = promise.Wait(timeout.Multiply(3)); Assert.Fail("Should have thrown"); } catch (Exception exc) { stopwatch.Stop(); Exception baseExc = exc.GetBaseException(); if (!(baseExc is TimeoutException)) { Assert.Fail("Should not have got here " + exc); } } output.WriteLine("Waited for " + stopwatch.Elapsed); Assert.IsTrue(!finished); Assert.IsTrue(stopwatch.Elapsed >= timeout.Multiply(0.9), "Waited less than " + timeout.Multiply(0.9) + ". Waited " + stopwatch.Elapsed); Assert.IsTrue(stopwatch.Elapsed <= timeout.Multiply(2), "Waited longer than " + timeout.Multiply(2) + ". Waited " + stopwatch.Elapsed); Assert.IsTrue(promise.Status == TaskStatus.Faulted); // try to re-use the promise and should fail immideately. try { stopwatch = new Stopwatch(); promise.Wait(); Assert.Fail("Should have thrown"); } catch (Exception exc) { stopwatch.Stop(); Exception baseExc = exc.GetBaseException(); if (!(baseExc is TimeoutException)) { Assert.Fail("Should not have got here " + exc); } } Assert.IsTrue(stopwatch.Elapsed <= timeout.Multiply(0.1), "Waited longer than " + timeout.Multiply(0.1) + ". Waited " + stopwatch.Elapsed); Assert.IsTrue(promise.Status == TaskStatus.Faulted); }
private ITestObject GetBoundedInstance(string title, IObjectSpec spec) { if (spec.GetFacet <IBoundedFacet>() == null) { Assert.Fail(spec.SingularName + " is not a Bounded type"); } IEnumerable allInstances = NakedObjectsFramework.Persistor.Instances(spec); var inst = allInstances.Cast <object>().Single(o => NakedObjectsFramework.NakedObjectManager.CreateAdapter(o, null, null).TitleString() == title); return(TestObjectFactoryClass.CreateTestObject(NakedObjectsFramework.NakedObjectManager.CreateAdapter(inst, null, null))); }
public async Task Sched_AC_WaitTest() { int n = 0; bool insideTask = false; UnitTestSchedulingContext context = new UnitTestSchedulingContext(); orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context); var result = new TaskCompletionSource <bool>(); orleansTaskScheduler.QueueWorkItem(new ClosureWorkItem(() => { var task1 = Task.Factory.StartNew(() => { output.WriteLine("Starting 1"); Assert.IsFalse(insideTask, "Starting new task when I am already inside task of iteration {0}", n); insideTask = true; output.WriteLine("===> 1a"); Thread.Sleep(1000); n = n + 3; output.WriteLine("===> 1b"); insideTask = false; }); var task2 = Task.Factory.StartNew(() => { output.WriteLine("Starting 2"); Assert.IsFalse(insideTask, "Starting new task when I am alraedy inside task of iteration {0}", n); insideTask = true; output.WriteLine("===> 2a"); task1.Wait(); output.WriteLine("===> 2b"); n = n * 5; output.WriteLine("===> 2c"); insideTask = false; result.SetResult(true); }); task1.Ignore(); task2.Ignore(); }), context); var timeoutLimit = TimeSpan.FromMilliseconds(1500); try { await result.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.Fail("Result did not arrive before timeout " + timeoutLimit); } Assert.IsTrue(n != 0, "Work items did not get executed"); Assert.AreEqual(15, n, "Work items executed out of order"); }
protected virtual ITestService GetTestService(Type type) { var testService = NakedObjectsFramework.ServicesManager.GetServices(). Where(no => type.IsInstanceOfType(no.Object)). Select(no => TestObjectFactoryClass.CreateTestService(no.Object)). FirstOrDefault(); if (testService == null) { Assert.Fail("No service of type " + type); } return(testService); }
public void CastFailInternalCastFromBadType() { Xunit.Assert.Throws <InvalidCastException>(() => { Type t = typeof(ISimpleGrain); GrainReference grain = (GrainReference)GrainClient.GrainFactory.GetGrain <ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix); IAddressable cast = GrainReference.CastInternal( typeof(Boolean), null, grain, GrainInterfaceUtils.GetGrainInterfaceId(t)); Assert.Fail("Exception should have been raised"); }); }