public void Expect_that_a_serialized_object_can_be_deserialized_accurately() { var objIn = new TestState { A = decimal.MaxValue, B = "Hello World!", C = DateTime.MaxValue, D = long.MaxValue, E = new byte[] { 1, 2, 3 }, F = true }; var ms = new MemoryStream(128); var serializer = new Serializer(); serializer.Serialize(ms, objIn); ms.Position = 0; var objOut = serializer.Deserialize<TestState>(ms); Assert.That(objOut.A == objIn.A); Assert.That(objOut.B == objIn.B); Assert.That(objOut.C == objIn.C); Assert.That(objOut.D == objIn.D); Assert.That(objOut.E.SequenceEqual(objIn.E)); Assert.That(objOut.F == objIn.F); }
public async Task CookiesOnTheRequestAndInTheContainer() { // ARRANGE var ts = new TestState { Request = { Headers = { {"Cookie", "a=1; b=2"}, {"cookie", "c=3; "}, {"COOKIE", "d=4;"}, {"cOOKIE", "e=5"} } } }; ts.CookieContainer.Add(ts.Uri, new Cookie("f", "6")); ts.CookieContainer.Add(ts.Uri, new Cookie("g", "7")); // ACT await ts.HttpClient.SendAsync(ts.Request); // ASSERT ts.VerifyRequestCookie("a=1; b=2; c=3; d=4; e=5; f=6; g=7"); }
private class FooComponent : IGameComponent { public bool Enabled { get; set; } public string Test = "Foo"; public void Update()
public TestTreeNode(string name, TestNodeType nodeType) { this.name=name; this.nodeType = nodeType; this.state = TestState.NotRun; this.nodes = new TestTreeNodeCollection(this); }
public async Task It_Reads_Multiple_Chunks_With_A_Large_Buffer_Asynchronously() { // ARRANGE var ts = new TestState { BufferSize = 1024 }; // ACT, ASSERT await ts.ReadAndVerifyAsync(ts.MultipleChunks); }
public void It_Reads_One_Chunk_Synchronously() { // ARRANGE var ts = new TestState(); // ACT, ASSERT ts.ReadAndVerify(ts.MultipleChunks); }
public void It_Reads_Multiple_Chunks_With_A_Large_Buffer_Synchronously() { // ARRANGE var ts = new TestState { BufferSize = 1024 }; // ACT, ASSERT ts.ReadAndVerify(ts.MultipleChunks); }
public async Task It_Reads_One_Chunk_Asynchronously() { // ARRANGE var ts = new TestState(); // ACT, ASSERT await ts.ReadAndVerifyAsync(ts.MultipleChunks); }
public async Task It_Returns_All_Contents_With_A_Large_Buffer() { // ARRANGE var ts = new TestState(); // ACT, ASSERT await ts.VerifyReadLineThenReadBytesAsync(ts.TrailingLineEndings, ts.GetLength(ts.TrailingLineEndings) * 2); }
public void Fail(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); this.Stop(); this.state = TestState.Failure; this.exception = exception; }
} public void Enable() { } public void Disable()
} } private class BarComponent : IGameComponent { public bool Enabled { get; set; } public string Test = "Bar";
public async Task It_Can_Read_All_Lines_With_Trailing_Line_Endings() { // ARRANGE var ts = new TestState(); // ACT, ASSERT await ts.VerifyAllLinesAsync(ts.TrailingLineEndings); }
private void Process(string displayName, TestState state, string output = "") { Console.WriteLine($"{state} - {displayName}"); var result = new TestResultData(displayName, state, output); _writer.Write(TestDataKind.Value); _writer.Write(result); }
public async Task It_Returns_Correct_Line_With_Large_Buffer() { // ARRANGE var ts = new TestState(); ts.BufferSize = ts.GetLength(ts.TwoLines) * 2; // ACT, ASSERT await ts.VerifyAllLinesAsync(ts.TwoLines); }
public void Update(Result result) { if (result == null) throw new ArgumentNullException("result"); this.state = result.State; if (result.Exception != null) this.exception = XmlException.FromException(result.Exception); this.Update(result.Monitor); }
{ } public void Enable() { }
public void Big_long_expressions_work(TestState testState, TestType testType, string expected) { var actual = _queryStringBuilder .QueryStringWith(testState == TestState.All ? "" : "state=" + testState.ToString().EnumNameToTransportCase()) .AndWith(testType == TestType.All ? "" : "type=" + testType.ToString().EnumNameToTransportCase()) .Build(); actual.Should().Be(expected); }
public TestResult(string runner, string assembly, string fixture, double milliseconds, string testName, TestState state, string message) { Runner = runner; Assembly = assembly; TestFixture = fixture; DurationInMilliseconds = milliseconds; TestName = testName; State = state; Message = message; }
} } [Test] public void ShouldAddComponentToGameState() { var state = new TestState(); Assert.False(state.HasComponent(typeof (FooComponent))); var comp = state.AddComponent(new FooComponent()); Assert.True(state.HasComponent(comp));
public async Task NoCookies() { // ARRANGE var ts = new TestState(); // ACT await ts.HttpClient.SendAsync(ts.Request); // ASSERT ts.VerifyEmptyCookieContainer(); }
public static int CompareToForSorting(this TestState a, TestState b) { if (a == b) { return 0; } int aOrderId = GetOrderId(a); int bOrderId = GetOrderId(b); return aOrderId - bOrderId; }
public void Add_WithoutNullState_DoesNotThrowAnException() { // Arrange var state = new TestState(); var subject = CreateSubject(); // Act Action act = () => subject.Add(state); // Assert act(); }
public TestCaseViewModel(string displayName, string skipReason, string assemblyFileName, IEnumerable<TraitViewModel> traits) { this.DisplayName = displayName; this.SkipReason = skipReason; this.AssemblyFileName = assemblyFileName; this.Traits = traits.ToImmutableArray(); if (!string.IsNullOrEmpty(skipReason)) { _state = TestState.Skipped; } }
public async Task It_Can_Trim_Line_Endings() { // ARRANGE var ts = new TestState {PreserveLineEndings = false}; ts.Setup(ts.OneLine); // ACT string line = await ts.Reader.ReadLineAsync(); // ASSERT ts.OneLine.First().Trim().Should().Be(line); }
public void Add_WithoutNullState_DoesNotThrowAnException() { // Arrange var state = new TestState(); var subject = new BreadthFirstSearchFringe<TestState>(); // Act Action act = () => subject.Add(state); // Assert act(); }
public static TestResult ToTdNetTestResult(this ITestResultMessage testResult, TestState testState) { return new TestResult { FixtureType = testResult.TestCase.GetClass(), Method = testResult.TestCase.GetMethod(), Name = testResult.TestDisplayName, State = testState, TimeSpan = new TimeSpan((long)(10000.0M * testResult.ExecutionTime)), TotalTests = 1, }; }
protected override string GetCaption() { var count = testCases.Count(); var caption = String.Format("<b>{0}</b><br>", sourceName); if (count == 0) { caption += "<font color='#ff7f00'>no test was found inside this suite</font>"; } else { var outcomes = testCases.GroupBy(r => r.Result); var results = outcomes.ToDictionary(k => k.Key, v => v.Count()); int positive; results.TryGetValue(TestState.Passed, out positive); int failure; results.TryGetValue(TestState.Failed, out failure); int skipped; results.TryGetValue(TestState.Skipped, out skipped); int notRun; results.TryGetValue(TestState.NotRun, out notRun); // No failures and all run if (failure == 0 && notRun == 0) { caption += string.Format("<font color='green'><b>Success!</b> {0} test{1}</font>", positive, positive == 1 ? string.Empty : "s"); result = TestState.Passed; } else if (failure > 0 || (notRun > 0 && notRun < count)) { // we either have failures or some of the tests are not run caption += String.Format("<font color='green'>{0} success,</font> <font color='red'>{1} failure{2}, {3} skip{4}, {5} not run</font>", positive, failure, failure > 1 ? "s" : String.Empty, skipped, skipped > 1 ? "s" : String.Empty, notRun); result = TestState.Failed; } else if (Result == TestState.NotRun) { caption += String.Format("<font color='green'><b>{0}</b> test case{1}, <i>{2}</i></font>", count, count == 1 ? String.Empty : "s", Result); } } return caption; }
public void GetNext_WhenTheFringeIsNotEmpty_ShouldReturnAnAddedItem() { // Arrange var expected = new TestState(); var subject = new BreadthFirstSearchFringe<TestState>(); subject.Add(expected); // Act var result = subject.GetNext(); // Assert Assert.Equal(expected, result); }
public void Constructor() { // arrange var server = new Mock<IConsensusServerStateApi>().Object; // assert Assert.That(() => new TestState(null), Throws.InstanceOf<ArgumentNullException>()); // act var state = new TestState(server); // assert Assert.That(state.PublicServer, Is.SameAs(server)); }
public CartExpiredEvent(TestState state) { _state = state; }
public void tstore_from_nonstatic_reentrant_call_with_static_intermediary(Instruction callType, int expectedResult) { // If caller is self, TLOAD and return value (break recursion) // Else, TSTORE and call self, return the response byte[] contractCode = Prepare.EvmCode // Check call depth .PushData(0) .Op(Instruction.CALLDATALOAD) // Store input in mem and reload it to stack .DataOnStackToMemory(5) .PushData(5) .Op(Instruction.MLOAD) // See if we're at call depth 1 .PushData(1) .Op(Instruction.EQ) .PushData(84) .Op(Instruction.JUMPI) // See if we're at call depth 2 .PushData(5) .Op(Instruction.MLOAD) .PushData(2) .Op(Instruction.EQ) .PushData(140) .Op(Instruction.JUMPI) // Call depth = 0, call self after TSTORE 8 .StoreDataInTransientStorage(1, 8) // Recursive call with input // Depth++ .PushData(5) .Op(Instruction.MLOAD) .PushData(1) .Op(Instruction.ADD) .DynamicCallWithInput(callType, TestItem.AddressD, 50000) // TLOAD and return value .LoadDataFromTransientStorage(1) .DataOnStackToMemory(0) .PushData(32) .PushData(0) .Op(Instruction.RETURN) // Call depth 1, TSTORE 9 but REVERT after recursion .Op(Instruction.JUMPDEST) // PC = 84 // Recursive call with input // Depth++ .PushData(5) .Op(Instruction.MLOAD) .PushData(1) .Op(Instruction.ADD) .CallWithInput(TestItem.AddressD, 50000) // TLOAD and return value .LoadDataFromTransientStorage(1) .DataOnStackToMemory(0) .PushData(32) .PushData(0) .Op(Instruction.RETURN) // Call depth 2, TSTORE 10 and complete .Op(Instruction.JUMPDEST) // PC = 140 .StoreDataInTransientStorage(1, 10) // This will fail .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); Keccak contractCodeHash = TestState.UpdateCode(contractCode); TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode .CallWithInput(TestItem.AddressD, 50000, new byte[32]) .ReturnInnerCallResult() .Done; TestAllTracerWithOutput result = Execute(MainnetSpecProvider.ShanghaiBlockNumber, 100000, code); // Should be original TSTORE value Assert.AreEqual(expectedResult, (int)result.ReturnValue.ToUInt256()); }
public EditorImguiTestFinishedEventArgs(TestState result) { Result = result; }
static void CheckState(Pointer mouse, ref TestState state) { state.m_PreviousMousePosition = mouse.position.ReadValue(); state.m_PreviousDelta = mouse.delta.ReadValue(); }
public ValidateAddressRequest(TestState instance) { _instance = instance; }
public IEnumerator StateMachine() { TestRunnerCallback.RunStarted(Application.platform.ToString(), m_TestComponents); while (true) { if (!m_TestsProvider.AnyTestsLeft() && currentTest == null) { FinishTestRun(); yield break; } if (currentTest == null) { StartNewTest(); } if (currentTest != null) { if (m_TestState == TestState.Running) { if (currentTest.ShouldSucceedOnAssertions()) { var assertionsToCheck = currentTest.gameObject.GetComponentsInChildren <AssertionComponent>().Where(a => a.enabled).ToArray(); if (assertionsToCheck.Any() && assertionsToCheck.All(a => a.checksPerformed > 0)) { IntegrationTest.Pass(currentTest.gameObject); m_TestState = TestState.Success; } } if (currentTest != null && Time.time > m_StartTime + currentTest.GetTimeout()) { m_TestState = TestState.Timeout; } } switch (m_TestState) { case TestState.Success: LogMessage(k_FinishedMessage); FinishTest(TestResult.ResultType.Success); break; case TestState.Failure: LogMessage(k_FailedMessage); FinishTest(TestResult.ResultType.Failed); break; case TestState.Exception: LogMessage(k_FailedExceptionMessage); FinishTest(TestResult.ResultType.FailedException); break; case TestState.Timeout: LogMessage(k_TimeoutMessage); FinishTest(TestResult.ResultType.Timeout); break; case TestState.Ignored: LogMessage(k_IgnoredMessage); FinishTest(TestResult.ResultType.Ignored); break; } } yield return(null); } }
public MemberRegisteredImpl(TestState state) { _state = state; }
void DrawOpenNodes(TestState state) { if (state.OpenNodes == null) { return; } int nodeCount = state.OpenNodes.Count; if (nodeCount == 0) { return; } Vector3[] verts = new Vector3[nodeCount * 4]; int[] indecs = new int[nodeCount * 6]; Color[] colors = new Color[nodeCount * 4]; int v = 0; int i = 0; for (int k = 0; k < nodeCount; ++k) { PathingNode node = state.OpenNodes[k]; verts[v] = new Vector3(node.Location.x, 0, node.Location.y); verts[v + 1] = new Vector3(node.Location.x, 0, node.Location.y + 1); verts[v + 2] = new Vector3(node.Location.x + 1, 0, node.Location.y + 1); verts[v + 3] = new Vector3(node.Location.x + 1, 0, node.Location.y); Color color = state.VisitedNodes.Contains(node) ? state.VisitedNodeColor : state.OpenNodeColor; colors[v] = colors[v + 1] = colors[v + 2] = colors[v + 3] = color; indecs[i++] = v; indecs[i++] = v + 1; indecs[i++] = v + 2; indecs[i++] = v; indecs[i++] = v + 2; indecs[i++] = v + 3; v += 4; } string childName = state.Name + "_OpenNodes"; Transform child = transform.Find(childName); if (child == null) { child = new GameObject(childName).transform; child.SetParent(transform); child.localPosition = new Vector3(0, 0.1f, 0); } Mesh mesh = new Mesh(); mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; mesh.vertices = verts; mesh.triangles = indecs; mesh.colors = colors; MeshFilter mf = child.gameObject.GetComponent <MeshFilter>(); if (mf == null) { mf = child.gameObject.AddComponent <MeshFilter>(); } mf.sharedMesh = mesh; MeshRenderer mr = child.gameObject.GetComponent <MeshRenderer>(); if (mr == null) { mr = child.gameObject.AddComponent <MeshRenderer>(); Material mat = new Material(Shader.Find("Unlit/NewUnlitColor")); //mat.SetColor("_Color", state.OpenNodeColor); mr.material = mat; } }
public MyCustomTest() { this._state = new FixtureState(this); }
public void Verify_Multiple_Operations_Buffer_Independently() { var updates = new List <TestStateAtomicStream>(); var testState = new TestState(); var testSubscription = testState.AtomicStream.Subscribe(updates.Add); var atomicStreamSubscription = testState.AtomicStream.Connect(); testState.CompleteUpdateOperation(); testState.UpdateCacheProperty(x => x.Data1Cache, u => { u.AddOrUpdate(new TestStateType1 { Id = Guid.NewGuid(), Name = "testingName1" }); u.AddOrUpdate(new TestStateType1 { Id = Guid.NewGuid(), Name = "testingName2" }); }); testState.UpdateCacheProperty(x => x.Data2Cache, u => { u.AddOrUpdate(new TestStateType2 { Id = Guid.NewGuid(), Description = "testingDescription1" }); u.AddOrUpdate(new TestStateType2 { Id = Guid.NewGuid(), Description = "testingDescription2" }); }); testState.CompleteUpdateOperation(); testState.CompleteUpdateOperation(); testState.UpdateCacheProperty(x => x.Data1Cache, u => { u.AddOrUpdate(new TestStateType1 { Id = Guid.NewGuid(), Name = "testingName1" }); u.AddOrUpdate(new TestStateType1 { Id = Guid.NewGuid(), Name = "testingName2" }); }); testState.CompleteUpdateOperation(); testState.UpdateCacheProperty(x => x.Data2Cache, u => { u.AddOrUpdate(new TestStateType2 { Id = Guid.NewGuid(), Description = "testingDescription1" }); u.AddOrUpdate(new TestStateType2 { Id = Guid.NewGuid(), Description = "testingDescription2" }); }); testState.CompleteUpdateOperation(); atomicStreamSubscription.Dispose(); testSubscription.Dispose(); Assert.Equal(5, updates.Count); Assert.Equal(0, updates[0].Data1.Count); Assert.Equal(0, updates[0].Data2.Count); Assert.Equal(0, updates[0].Data3.Count); Assert.Equal(2, updates[1].Data1.Count); Assert.Equal(2, updates[1].Data2.Count); Assert.Equal(0, updates[0].Data3.Count); Assert.Equal(0, updates[2].Data1.Count); Assert.Equal(0, updates[2].Data2.Count); Assert.Equal(0, updates[0].Data3.Count); Assert.Equal(2, updates[3].Data1.Count); Assert.Equal(0, updates[3].Data2.Count); Assert.Equal(0, updates[0].Data3.Count); Assert.Equal(0, updates[4].Data1.Count); Assert.Equal(2, updates[4].Data2.Count); Assert.Equal(0, updates[0].Data3.Count); }
public void Verify_Multiple_Updates_To_Multiple_Properties_Merge() { var updates = new List <TestStateAtomicStream>(); var testState = new TestState(); var testSubscription = testState.AtomicStream.Subscribe(updates.Add); var atomicStreamSubscription = testState.AtomicStream.Connect(); testState.UpdateCacheProperty(x => x.Data1Cache, u => { u.AddOrUpdate(new TestStateType1 { Id = Guid.NewGuid(), Name = "testingName1" }); u.AddOrUpdate(new TestStateType1 { Id = Guid.NewGuid(), Name = "testingName2" }); }); testState.UpdateCacheProperty(x => x.Data2Cache, u => { u.AddOrUpdate(new TestStateType2 { Id = Guid.NewGuid(), Description = "testingDescription1" }); u.AddOrUpdate(new TestStateType2 { Id = Guid.NewGuid(), Description = "testingDescription2" }); }); testState.UpdateCacheProperty(x => x.Data1Cache, u => { u.AddOrUpdate(new TestStateType1 { Id = Guid.NewGuid(), Name = "testingName3" }); u.AddOrUpdate(new TestStateType1 { Id = Guid.NewGuid(), Name = "testingName4" }); }); testState.UpdateCacheProperty(x => x.Data2Cache, u => { u.AddOrUpdate(new TestStateType2 { Id = Guid.NewGuid(), Description = "testingDescription3" }); u.AddOrUpdate(new TestStateType2 { Id = Guid.NewGuid(), Description = "testingDescription4" }); }); testState.CompleteUpdateOperation(); atomicStreamSubscription.Dispose(); testSubscription.Dispose(); Assert.Equal(1, updates.Count); Assert.Equal(4, updates[0].Data1.Count); Assert.Equal(4, updates[0].Data2.Count); Assert.Equal(0, updates[0].Data3.Count); }
static void Main(string[] args) { TestBridge cls1 = new TestBridge(); cls1.Execute(); TestFactory cls5 = new TestFactory(); cls5.Execute(); TestBuilder cls15 = new TestBuilder(); cls15.Execute(); TestPrototype cls9 = new TestPrototype(); cls9.Execute(); TestObserver cls7 = new TestObserver(); cls7.Execute(); TestAdaptor cls = new TestAdaptor(); cls.Execute(); TestDecorater cls4 = new TestDecorater(); cls4.Execute(); TestComposite cls3 = new TestComposite(); cls3.Execute(); TestProxy cls10 = new TestProxy(); cls10.Execute(); TestIterator cls6 = new TestIterator(); cls6.Execute(); TestState cls14 = new TestState(); cls14.Execute(); TestCommand cls2 = new TestCommand(); cls2.Execute(); // ************ TestProducerConsumer cls8 = new TestProducerConsumer(); cls8.Execute(); TestReaderWriter cls11 = new TestReaderWriter(); cls11.Execute(); TestSimpleThread cls12 = new TestSimpleThread(); cls12.Execute(); TestSingleton cls13 = new TestSingleton(); cls13.Execute(); }
State GetCurrentState(TestState state) { return(_machine.GetState(state).Result); }
static Stream DoOutputStream(TestState state, bool accessed) { bool?canCalled = accessed ? (bool?)true : null; return(DoStream(state, null, canCalled)); }
protected void AssertCodeHash(Address address, Keccak codeHash) { Assert.AreEqual(codeHash, TestState.GetCodeHash(address), "code hash"); }
/// <summary> /// Initializes the <see cref="TestState"/> for a new spec. /// </summary> /// <param name="system">The actor system this test will use. Can be null.</param> /// <param name="config">The configuration that <paramref name="system"/> will use if it's null.</param> /// <param name="actorSystemName">The name that <paramref name="system"/> will use if it's null.</param> /// <param name="testActorName">The name of the test actor. Can be null.</param> protected void InitializeTest(ActorSystem system, ActorSystemSetup config, string actorSystemName, string testActorName) { _testState = new TestState(); if (system == null) { var bootstrap = config.Get <BootstrapSetup>(); var configWithDefaultFallback = bootstrap.HasValue ? bootstrap.Value.Config.Select(c => c == _defaultConfig ? c : c.WithFallback(_defaultConfig)) : _defaultConfig; var newBootstrap = BootstrapSetup.Create().WithConfig( configWithDefaultFallback.HasValue ? configWithDefaultFallback.Value : _defaultConfig); if (bootstrap.FlatSelect(x => x.ActorRefProvider).HasValue) { newBootstrap = newBootstrap.WithActorRefProvider(bootstrap.FlatSelect(x => x.ActorRefProvider).Value); } system = ActorSystem.Create(actorSystemName ?? "test", config.WithSetup(newBootstrap)); } _testState.System = system; system.RegisterExtension(new TestKitExtension()); system.RegisterExtension(new TestKitAssertionsExtension(_assertions)); _testState.TestKitSettings = TestKitExtension.For(_testState.System); _testState.Queue = new BlockingQueue <MessageEnvelope>(); _testState.Log = Logging.GetLogger(system, GetType()); _testState.EventFilterFactory = new EventFilterFactory(this); //register the CallingThreadDispatcherConfigurator _testState.System.Dispatchers.RegisterConfigurator(CallingThreadDispatcher.Id, new CallingThreadDispatcherConfigurator(_testState.System.Settings.Config, _testState.System.Dispatchers.Prerequisites)); if (string.IsNullOrEmpty(testActorName)) { testActorName = "testActor" + _testActorId.IncrementAndGet(); } var testActor = CreateTestActor(system, testActorName); //Wait for the testactor to start // Calling sync version here, since .Wait() causes deadlock AwaitCondition(() => { return(!(testActor is IRepointableRef repRef) || repRef.IsStarted); }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10)); if (!(this is INoImplicitSender)) { InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying; } else if (!(this is TestProbe)) //HACK: we need to clear the current context when running a No Implicit Sender test as sender from an async test may leak //but we should not clear the current context when creating a testprobe from a test { InternalCurrentActorCellKeeper.Current = null; } SynchronizationContext.SetSynchronizationContext( new ActorCellKeepingSynchronizationContext(InternalCurrentActorCellKeeper.Current)); _testState.TestActor = testActor; }
public void EffectiveBalanceHysteresis() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); //# Prepare state up to the final-updates. //# Then overwrite the balances, we only want to focus to be on the hysteresis based changes. TestProcessUtility.RunEpochProcessingTo(testServiceProvider, state, TestProcessStep.ProcessFinalUpdates); GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; BeaconChainUtility beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>(); BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); // Set some edge cases for balances Gwei maximum = gweiValues.MaximumEffectiveBalance; Gwei minimum = gweiValues.EjectionBalance; Gwei increment = gweiValues.EffectiveBalanceIncrement; Gwei halfIncrement = increment / 2; EffectiveBalanceCase[] testCases = new[] { new EffectiveBalanceCase(maximum, maximum, maximum, "as-is"), new EffectiveBalanceCase(maximum, (Gwei)(maximum - 1), maximum - increment, "round down, step lower"), new EffectiveBalanceCase(maximum, (Gwei)(maximum + 1), maximum, "round down"), new EffectiveBalanceCase(maximum, (Gwei)(maximum - increment), maximum - increment, "exactly 1 step lower"), new EffectiveBalanceCase(maximum, (Gwei)(maximum - increment - 1), maximum - (increment * 2), "just 1 over 1 step lower"), new EffectiveBalanceCase(maximum, (Gwei)(maximum - increment + 1), maximum - increment, "close to 1 step lower"), new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 3)), minimum, "bigger balance, but not high enough"), new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 3) + 1), minimum + increment, "bigger balance, high enough, but small step"), new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 4) - 1), minimum + increment, "bigger balance, high enough, close to double step"), new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 4)), minimum + (increment * 2), "exact two step balance increment"), new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 4) + 1), minimum + (increment * 2), "over two steps, round down"), }; Epoch currentEpoch = beaconStateAccessor.GetCurrentEpoch(state); for (int index = 0; index < testCases.Length; index++) { Validator validator = state.Validators[index]; bool isActive = beaconChainUtility.IsActiveValidator(validator, currentEpoch); isActive.ShouldBeTrue(); EffectiveBalanceCase testCase = testCases[index]; validator.SetEffectiveBalance(testCase.PreEffective); ValidatorIndex validatorIndex = new ValidatorIndex((ulong)index); state.SetBalance(validatorIndex, testCase.Balance); } // Act beaconStateTransition.ProcessFinalUpdates(state); // Assert for (int index = 0; index < testCases.Length; index++) { EffectiveBalanceCase testCase = testCases[index]; Validator validator = state.Validators[index]; validator.EffectiveBalance.ShouldBe(testCase.PostEffective, testCase.Name); } }
public ValidateNameRequest(TestState instance) { _instance = instance; }
private async Task <TechnicalOutcome> Do(Point point, bool suppressExceptionsIntoResult, TestState testState, int testCaseId, CancellationToken cancelToken) { foreach (var step in point.TestSteps) { if (cancelToken.IsCancellationRequested) { break; } point.RunOk = true; if (!suppressExceptionsIntoResult) { testState = await ExecuteTestStep(point, step, testState, cancelToken); } else { try { testState = await ExecuteTestStep(point, step, testState, cancelToken); } catch (WebDriverException we) when(we.Message.Contains("Variable Resource Not Found")) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (WebDriverException we) when(we.Message.Contains("Only one usage of each socket address")) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (WebDriverException we) when( we.Message.Contains("The HTTP request to the remote WebDriver server for URL") && we.Message.Contains("timed out")) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (NoSuchWindowException we) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (FailureToStartTestException we) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (InvalidOperationException we) when(we.Message.Contains("unable to send message to renderer")) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (Exception e) { step.Result = e is TestCaseException?TestStepResult.Failed(e.Message) : TestStepResult.ImplementationError(e); step.Result.RefToScreenshot = ErrorCollector.GetReferenceToAttachmentIfApplicable(testState); Console.WriteLine("For point in testcase " + point.Id + "; screenshot uploaded to " + step.Result.RefToScreenshot); step.Result.SetException(e); point.RunOk = false; _logger.Error(e); break; } } if (!step.Result.Success) { step.Result.RefToScreenshot = ErrorCollector.GetReferenceToAttachmentIfApplicable(testState); Console.WriteLine("For point in testcase " + point.Id + "; screenshot uploaded to " + step.Result.RefToScreenshot); point.RunOk = false; break; } } for (var i = point.TestSteps.Count - 1; i >= 0; i--) { var step = point.TestSteps[i]; try { CleanupTestStep(point, step, testState); } catch (Exception e) { _logger.Error($"Cleanup Failed for Point {point.Id} in Step {step.StepIndex} of TC {testCaseId}: {e.Message}"); } } return(TechnicalOutcome.Ok); }
public TestState Apply(TestState state, CountChangedClassEvent @event) { state.Count = @event.NewCount; return(state); }
internal static TestState Init(Options options) { var state = new TestState(); // var aMock = new Mock <Android.Bluetooth.BluetoothAdapter>(MockBehavior.Strict); state.AddMock(aMock); //-- var dMock = new Mock <Android.Bluetooth.BluetoothDevice>(MockBehavior.Strict); state.AddMock(dMock); //-- // Socket Func <BluetoothSocket> setupSocketConnectStop = delegate() { var sMock = new Mock <BluetoothSocket>(MockBehavior.Strict); state.AddMock(sMock); if (GetValueOrReport(() => options.Connect)) { sMock.Setup(x => x.Connect()) ; //.Callback(doConnect); if (true) { bool gs = GetValueOrReport(() => options.GetStream1); //bool? gs = gsV ? true : (bool?)null; sMock.Setup(x => x.InputStream).Returns(DoInputStream(state, gs)); sMock.Setup(x => x.OutputStream).Returns(DoOutputStream(state, gs)); } } if (GetValueOrReport(() => options.ClientDispose)) { sMock.Setup(x => x.Close()).Callback(() => { }); } return(sMock.Object); }; // CreateSocket Moq.Language.Flow.ISetup <BluetoothDevice, BluetoothSocket> setupDeviceCreateSocket; if (GetValueOrReport(() => options.CreateSocket)) { if (GetValueOrReport(() => options.Insecure)) { setupDeviceCreateSocket = dMock.Setup(x => x.CreateInsecureRfcommSocketToServiceRecord( It.IsAny <UUID>())); // TODO ! } else { setupDeviceCreateSocket = dMock.Setup(x => x.CreateRfcommSocketToServiceRecord( It.IsAny <UUID>())); // TODO ! } setupDeviceCreateSocket.Returns(setupSocketConnectStop); } // BluetoothClass Func <BluetoothClass> setupDeviceGetClass = delegate { var cMock = new Mock <BluetoothClass>(); return(cMock.Object); }; // GetRemoteDevice //-Func<BluetoothDevice> setupAdapterGetDevice= delegate // Func <UUID> doUUID = () => { var uMock = new Mock <UUID>(Guid.Empty); return(uMock.Object); }; //---- // // Radio init aMock.Setup(x => x.Address).Returns("0000000000aa"); if (GetValueOrReport(() => options.GetRemoteDevice)) { // Device Init // TODO Have AndroidBtCli not need BondState/Class dMock.Setup(x => x.Address).Returns("0000000000dd"); //dMock.Setup(x => x.BondState).Returns((Bond)999); //dMock.Setup(x => x.BluetoothClass).Returns(setupDeviceGetClass); // Adapter init aMock.Setup(x => x.GetRemoteDevice( It.IsAny <string>())) //TODO .Returns(dMock.Object); } // var a = aMock.Object; //var f = new FooAndroidBthFactory(a); var fMock = new Mock <AndroidBthFactoryBase>(MockBehavior.Loose, a) { CallBase = true, }; fMock.Setup(x => x.ToJavaUuid(options.ExpectedSvcClass)) .Returns(doUUID); fMock.Setup(x => x.ToJavaUuid(It.IsAny <Guid>())) #if true .Throws(new AssertionException("Expected Service Class Guid not found."));
public TestState Apply(TestState state, ICountChangedInterfaceEvent @event) { state.Count = @event.NewCount; return(state); }
public TestRunEvent(Test test, TestState state) { _test = test; _state = state; }
public void Destroy_restore_store_different_cells_previously_existing() { byte[] baseInitCodeStore = Prepare.EvmCode .PushData(2) .Op(Instruction.CALLVALUE) .Op(Instruction.SSTORE).Done; byte[] contractCode = Prepare.EvmCode .PushData(1) .Op(Instruction.SLOAD) .PushData(1) .Op(Instruction.EQ) .PushData(17) .Op(Instruction.JUMPI) .PushData(1) .PushData(1) .Op(Instruction.SSTORE) .PushData(21) .Op(Instruction.JUMP) .Op(Instruction.JUMPDEST) .PushData(0) .Op(Instruction.SELFDESTRUCT) .Op(Instruction.JUMPDEST) .Done; byte[] baseInitCodeAfterStore = Prepare.EvmCode .ForInitOf(contractCode) .Done; byte[] baseInitCode = Bytes.Concat(baseInitCodeStore, baseInitCodeAfterStore); byte[] create2Code = Prepare.EvmCode .ForCreate2Of(baseInitCode) .Done; byte[] initOfCreate2Code = Prepare.EvmCode .ForInitOf(create2Code) .Done; Address deployingContractAddress = ContractAddress.From(TestItem.PrivateKeyA.Address, 0); Address deploymentAddress = ContractAddress.From(deployingContractAddress, new byte[32], baseInitCode); byte[] deploy = Prepare.EvmCode .CallWithValue(deployingContractAddress, 100000) .Op(Instruction.STOP).Done; byte[] byteCode1 = Prepare.EvmCode .CallWithValue(deploymentAddress, 100000) .Op(Instruction.STOP).Done; byte[] byteCode2 = Prepare.EvmCode .CallWithValue(deploymentAddress, 100000) .Op(Instruction.STOP).Done; TestState.CreateAccount(TestItem.PrivateKeyA.Address, 100.Ether()); //TestState.Commit(SpecProvider.GenesisSpec); //TestState.CommitTree(0); TestState.CreateAccount(deploymentAddress, UInt256.One); Keccak codeHash = TestState.UpdateCode(contractCode); TestState.UpdateCodeHash(deploymentAddress, codeHash, MuirGlacier.Instance); Storage.Set(new StorageCell(deploymentAddress, 7), new byte[] { 7 }); Storage.Commit(); Storage.CommitTrees(0); TestState.Commit(MuirGlacier.Instance); TestState.CommitTree(0); long gasLimit = 1000000; EthereumEcdsa ecdsa = new EthereumEcdsa(1, LimboLogs.Instance); // deploy create 2 Transaction tx0 = Build.A.Transaction.WithCode(initOfCreate2Code).WithGasLimit(gasLimit).SignedAndResolved(ecdsa, TestItem.PrivateKeyA).TestObject; // call contract once Transaction tx1 = Build.A.Transaction.WithCode(byteCode1).WithGasLimit(gasLimit).WithNonce(1).SignedAndResolved(ecdsa, TestItem.PrivateKeyA).TestObject; // self destruct contract Transaction tx2 = Build.A.Transaction.WithCode(byteCode2).WithGasLimit(gasLimit).WithNonce(2).SignedAndResolved(ecdsa, TestItem.PrivateKeyA).TestObject; // deploy again using create2 Transaction tx3 = Build.A.Transaction.WithValue(3).WithCode(deploy).WithGasLimit(gasLimit).WithNonce(3).SignedAndResolved(ecdsa, TestItem.PrivateKeyA).TestObject; // call newly deployed once Transaction tx4 = Build.A.Transaction.WithCode(byteCode1).WithGasLimit(gasLimit).WithNonce(4).SignedAndResolved(ecdsa, TestItem.PrivateKeyA).TestObject; Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(MuirGlacier.Instance, tx0, tx1, tx2, tx3, tx4).WithGasLimit(2 * gasLimit).TestObject; ParityLikeTxTracer tracer = new ParityLikeTxTracer(block, tx0, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); _processor.Execute(tx0, block.Header, tracer); tracer = new ParityLikeTxTracer(block, tx1, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); _processor.Execute(tx1, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 7), 7); tracer = new ParityLikeTxTracer(block, tx2, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); _processor.Execute(tx2, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 7), 0); tracer = new ParityLikeTxTracer(block, tx3, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); _processor.Execute(tx3, block.Header, tracer); AssertStorage(new StorageCell(deploymentAddress, 7), 0); tracer = new ParityLikeTxTracer(block, tx4, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); _processor.Execute(tx4, block.Header, tracer); AssertStorage(new StorageCell(deploymentAddress, 7), 0); }
public void Update() { TestState status = _service.GetStatus(_test); Status = determineStatus(status); }
private static TestState GetStateFromUFTResultsFile(string resultsFileFullPath, out string desc) { TestState finalState = TestState.Unknown; desc = ""; var status = ""; var doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(resultsFileFullPath); string strFileName = Path.GetFileName(resultsFileFullPath); if (strFileName.Equals("run_results.xml")) { XmlNodeList rNodeList = doc.SelectNodes("/Results/ReportNode/Data"); if (rNodeList == null) { desc = string.Format(Resources.XmlNodeNotExistError, "/Results/ReportNode/Data"); finalState = TestState.Error; } var node = rNodeList.Item(0); XmlNode resultNode = ((XmlElement)node).GetElementsByTagName("Result").Item(0); status = resultNode.InnerText; } else { var testStatusPathNode = doc.SelectSingleNode("//Report/Doc/NodeArgs"); if (testStatusPathNode == null) { desc = string.Format(Resources.XmlNodeNotExistError, "//Report/Doc/NodeArgs"); finalState = TestState.Error; } if (!testStatusPathNode.Attributes["status"].Specified) { finalState = TestState.Unknown; } status = testStatusPathNode.Attributes["status"].Value; } var result = (TestResult)Enum.Parse(typeof(TestResult), status); if (result == TestResult.Passed || result == TestResult.Done) { finalState = TestState.Passed; } else if (result == TestResult.Warning) { finalState = TestState.Warning; } else { finalState = TestState.Failed; } return(finalState); }
public CartRemovedEvent(TestState state) { _state = state; }
public void PIK_TestState() { CommandStart.StartWoStat(d => TestState.Start()); }
public TearDownState(TestState state) { this.currentTest = state.CurrentTest; this.profileId = state.ProfileId; }
public FixtureState(TestState state) { this.currentTest = state.CurrentTest; this.profileId = state.ProfileId; }