public void TestValidTransaction() { var snapshot = TestBlockchain.TheNeoSystem.GetSnapshot(); var walletA = TestUtils.GenerateTestWallet(); using var unlockA = walletA.Unlock("123"); var acc = walletA.CreateAccount(); // Fake balance var key = new KeyBuilder(NativeContract.GAS.Id, 20).Add(acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable <AccountState>().Balance = 100_000_000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction var tx = CreateValidTx(snapshot, walletA, acc.ScriptHash, 0); senderProbe.Send(system.Blockchain, tx); senderProbe.ExpectMsg <Blockchain.RelayResult>(p => p.Result == VerifyResult.Succeed); senderProbe.Send(system.Blockchain, tx); senderProbe.ExpectMsg <Blockchain.RelayResult>(p => p.Result == VerifyResult.AlreadyExists); }
public void EventAdapters_in_end_to_end_scenarios_should_use_the_same_adapter_when_reading_as_was_used_when_writing_to_journal() { WithActorSystem("SimpleSystem", AdaptersConfig, system => { var probe = new TestProbe(system, Assertions); var p1 = Persister("p1", probe, system); var a = new A("a1"); var b = new B("b1"); p1.Tell(a, probe.Ref); p1.Tell(b, probe.Ref); probe.ExpectMsg <A>(x => x.Payload.Equals("a1")); probe.ExpectMsg <B>(x => x.Payload.Equals("b1")); probe.Watch(p1); p1.Tell(PoisonPill.Instance); probe.ExpectTerminated(p1); var p11 = Persister("p1", probe, system); p11.Tell(GetState.Instance, probe.Ref); probe.ExpectMsg <A>(x => x.Payload.Equals("a1")); probe.ExpectMsg <B>(x => x.Payload.Equals("b1")); return(true); }); }
private WriteMessages ExpectWrite(IActorRef subject, params Msgs[] msgs) { var w = _journal.ExpectMsg <WriteMessages>(); w.PersistentActor.ShouldBe(subject); var messages = w.Messages.ToList(); messages.Count.ShouldBe(msgs.Length); for (int i = 0; i < messages.Count; i++) { var message = messages[i]; var msg = msgs[i]; if (message is AtomicWrite) { var aw = ((AtomicWrite)message); var writes = ((IEnumerable <IPersistentRepresentation>)aw.Payload).ToList(); writes.Count.ShouldBe(msg.Messages.Count); for (int j = 0; j < writes.Count; j++) { var p = writes[j]; var evt = p.Payload; evt.ShouldBe(msg.Messages[j]); } } else { Assertions.Fail("unexpected ", message); } } return(w); }
public void PersistentReceive_must_redeliver_lost_messages() { TestProbe probe = CreateTestProbe(); IActorRef dest = Sys.ActorOf(Props.Create(() => new Destination(probe.Ref))); var destinations = new Dictionary <string, ActorPath> { { "A", Sys.ActorOf(Props.Create(() => new Unreliable(3, dest))).Path } }; IActorRef sender = Sys.ActorOf( Props.Create( () => new Receiver(TestActor, Name, TimeSpan.FromMilliseconds(500), 5, 1000, false, destinations)), Name); sender.Tell(new Req("a-1")); ExpectMsg(ReqAck.Instance); probe.ExpectMsg <Action>(a => a.Id == 1 && a.Payload == "a-1"); sender.Tell(new Req("a-2")); ExpectMsg(ReqAck.Instance); probe.ExpectMsg <Action>(a => a.Id == 2 && a.Payload == "a-2"); sender.Tell(new Req("a-3")); sender.Tell(new Req("a-4")); ExpectMsg(ReqAck.Instance); ExpectMsg(ReqAck.Instance); // a-3 was lost ... probe.ExpectMsg <Action>(a => a.Id == 4 && a.Payload == "a-4"); // ... and then redelivered probe.ExpectMsg <Action>(a => a.Id == 3 && a.Payload == "a-3"); probe.ExpectNoMsg(TimeSpan.FromSeconds(1)); }
public void Test1(int cutoffSec) { // usage int expectedCount = 2; //선택 장애 장바구니 이벤트 Cmd cmd1 = new Cmd("장바구니를 물건을 담음+1"); Cmd cmd2 = new Cmd("장바구니에 물건을 뺌-0"); Cmd cmd3 = new Cmd("장바구니에 물건을 담음+1"); Cmd cmd4 = new Cmd("장바구니에 물건을 담음+2"); Within(TimeSpan.FromSeconds(cutoffSec), () => { persistentActor.Tell(cmd1); persistentActor.Tell(cmd2); persistentActor.Tell(cmd3); persistentActor.Tell(cmd4); persistentActor.Tell("print"); //현재까지 액터가 가진 이벤트리스트를 재생합니다. Assert.Equal(expectedCount, probe.ExpectMsg <int>()); //액터를 강제로 죽입니다. persistentActor.Tell(Kill.Instance); Task.Delay(500).Wait(); //시스템 셧다운후,재시작 시나리오 //액터를 다시생성하여, 액터가 가진 이벤트가 복구되는지 확인합니다. persistentActor = Sys.ActorOf(Props.Create(() => new MyPersistentActor(probe)), "persistentActor"); persistentActor.Tell("print"); Assert.Equal(expectedCount, probe.ExpectMsg <int>()); }); }
static void Main(string[] args) { TestKit testKit = new TestKit(); ActorSystem actorSystem = testKit.Sys; using (actorSystem) { // TestKit-based probe which allows sending, reception and reply. TestProbe probe = testKit.CreateTestProbe("test-probe"); IActorRef deviceActor = actorSystem.ActorOf(Device.Props("group", "device")); deviceActor.Tell(new RecordTemperature(requestId: 1, value: 24.0), probe.Ref); probe.ExpectMsg <TemperatureRecorded>(s => s.RequestId == 1); deviceActor.Tell(new ReadTemperature(requestId: 2), probe.Ref); RespondTemperature response1 = probe.ExpectMsg <RespondTemperature>(); response1.RequestId.Should().Be(2); response1.Value.Should().Be(24.0); deviceActor.Tell(new RecordTemperature(requestId: 3, value: 55.0), probe.Ref); probe.ExpectMsg <TemperatureRecorded>(s => s.RequestId == 3); deviceActor.Tell(new ReadTemperature(requestId: 4), probe.Ref); RespondTemperature response2 = probe.ExpectMsg <RespondTemperature>(); response2.RequestId.Should().Be(4); response2.Value.Should().Be(55.0); Console.WriteLine("UserMessage: App is finished."); // Exit the system after ENTER is pressed Console.ReadLine(); } }
public void MemoryStream_1024_BufferSize_512() { const int streamLength = 1024; const int bufferSize = 512; TestProbe owner = CreateTestProbe(name: "owner"); MemoryStream stream = CreateMemoryStream(streamLength); IActorRef readStream = ActorOf( ReadStream.Create("memory-stream-1024-buffer-size-512", owner, stream, bufferSize) ); Within(TimeSpan.FromSeconds(1), () => { // Exactly 2 packets for (int iteration = 0; iteration < streamLength / bufferSize; iteration++) { owner.ExpectMsg <ReadStream.StreamData>(streamData => { Assert.Equal(bufferSize, streamData.Data.Count); }); } owner.ExpectMsg <ReadStream.StreamData>(streamData => { Assert.Equal(0, streamData.Data.Count); Assert.True(streamData.IsEndOfStream); }); }); }
public void Enquirer_OnStart_MakesTry() { // Act enquirer.Tell(new Start()); // Assert chooser.ExpectMsg <TestTry>(t => t.Number == 50); }
/// <summary> /// Using region 2 as it is not shutdown in either test. /// </summary> private void PingEntities() { _region2.Tell(1, _probe2.Ref); _probe2.ExpectMsg <int>(10.Seconds()).Should().Be(1); _region2.Tell(2, _probe2.Ref); _probe2.ExpectMsg <int>(10.Seconds()).Should().Be(2); _region2.Tell(3, _probe2.Ref); _probe2.ExpectMsg <int>(10.Seconds()).Should().Be(3); }
public void WhenReceivesReadFileMessage_TellsCsvWriterActorToOpenEvenFile() { var actorInTest = CreateCsvReaderActor(); var filePath = "Dummy Path"; _streamReaderFactory.Setup(f => f.Create(filePath)).Returns(_streamReader); actorInTest.Tell(new ReadFile(filePath)); AwaitAssert(() => _csvWriterActor.ExpectMsg <EvenOpenFile>(), TimeSpan.FromSeconds(5)); }
public async Task CircuitBreaker_must_reply_with_special_failure_message_on_Write_requests_if_open() { var events = new[] { new DurableEvent("a", "emitter") }; breaker.Tell(ServiceEvent.Failed(LogId, 1, TestLogFailureException)); breaker.Tell(new Write(events, probe.Ref, probe.Ref, 1, 2)); probe.ExpectMsg(new WriteFailure(events, CircuitBreaker.Exception, 1, 2)); probe.Sender.Should().Be(probe.Ref); }
public void PersistentView_should_run_updates_on_user_request() { _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(5), null)); _viewProbe.ExpectMsg("replicated-a-1"); _viewProbe.ExpectMsg("replicated-b-2"); _pref.Tell("c"); _prefProbe.ExpectMsg("c-3"); _view.Tell(new Update(isAwait: false)); _viewProbe.ExpectMsg("replicated-c-3"); }
public async Task works_as_memory_journal_by_default() { var actor = ActorOf(() => new PersistActor(_probe)); await Journal.OnWrite.Pass(); actor.Tell("write", TestActor); _probe.ExpectMsg("ack"); }
public void TransferSaga_rollbacks_on_Deposit_request_failed() { Watch(transferSaga); Phase1(); Phase2(); transferSaga.Tell(new DepositFailed(transactionId, new Exception("TEST"))); accountsShardRegionProbe.ExpectMsg(new ShardEnvelope <Withdraw>(toAccountNr, new Withdraw(transactionId, amount))); ExpectMsg(new Deposit(transactionId, amount)); ExpectMsg <TransferFailed>(); ExpectTerminated(transferSaga); }
private IActorRef CreateAuthenticatedActor(TestProbe authenticationProbe, TestProbe clientSocketProbe) { //setup const uint CLIENTID = 1234567890; const string TOKEN = "TOKEN"; string EXPECTEDRESPONSE = $"HELLO {CLIENTID}"; var testeeRef = Sys.ActorOf(Props.Create(() => new ClientTwinActor(clientSocketProbe, authenticationProbe, defaultEndpoint, defaultShardRegionArea, defaultObjectRegionArea))); var clientHelloMessage = new ClientHelloMessage() { Message = string.Empty, ClientId = CLIENTID, ClientPort = 9999, Version = Shared.Constants.Version.PROTOCOL, }; var clientAuthenticationResponse = new ClientAuthenticationResponse() { AuthenticationToken = TOKEN, }; //execute - client hello testeeRef.Tell(new UdpTransferFrame(FrameType.ClientHello, clientHelloMessage.Serialize())); //verify clientSocketProbe.ExpectMsg <Udp.Send>(s => { var msg = new UdpTransferFrame(s.Payload.ToArray()); Assert.Equal(FrameType.ServerAuthenticationRequest, msg.Type); }); //execute - client authentication response testeeRef.Tell(new UdpTransferFrame(FrameType.ClientAuthenticationResponse, clientAuthenticationResponse.Serialize())); //verify authenticationProbe.ExpectMsg <RequestAuthenticationCommand>(c => { Assert.Equal(TOKEN, c.Token); }); //execute - authentication actor response testeeRef.Tell(new AuthenticationSuccess()); //verify clientSocketProbe.ExpectMsg <Udp.Send>(s => { var msg = new UdpTransferFrame(s.Payload.ToArray()); Assert.Equal(FrameType.ServerHello, msg.Type); var serverHello = new ServerHelloMessage(msg.MessageBuffer); Assert.Equal(EXPECTEDRESPONSE, serverHello.Message); Assert.Equal(clientHelloMessage.Version, serverHello.Version); }); return(testeeRef); }
public ClusterDomainEventPublisherSpec() : base(Config) { _memberSubscriber = CreateTestProbe(); Sys.EventStream.Subscribe(_memberSubscriber.Ref, typeof(ClusterEvent.IMemberEvent)); Sys.EventStream.Subscribe(_memberSubscriber.Ref, typeof(ClusterEvent.LeaderChanged)); Sys.EventStream.Subscribe(_memberSubscriber.Ref, typeof(ClusterEvent.ClusterShuttingDown)); _publisher = Sys.ActorOf(Props.Create <ClusterDomainEventPublisher>()); _publisher.Tell(new InternalClusterAction.PublishChanges(g0)); _memberSubscriber.ExpectMsg(new ClusterEvent.MemberUp(aUp)); _memberSubscriber.ExpectMsg(new ClusterEvent.LeaderChanged(aUp.Address)); }
public ClusterDomainEventPublisherSpec() { _memberSubscriber = CreateTestProbe(); Sys.EventStream.Subscribe(_memberSubscriber.Ref, typeof(ClusterEvent.IMemberEvent)); Sys.EventStream.Subscribe(_memberSubscriber.Ref, typeof(ClusterEvent.LeaderChanged)); _publisher = Sys.ActorOf(Props.Create <ClusterDomainEventPublisher>()); //TODO: If parent told of exception then test should fail (if not expected in some way)? _publisher.Tell(new InternalClusterAction.PublishChanges(g0)); _memberSubscriber.ExpectMsg(new ClusterEvent.MemberUp(aUp)); _memberSubscriber.ExpectMsg(new ClusterEvent.LeaderChanged(aUp.Address)); }
/// <summary> /// Using region 2 as it is not shutdown in either test. /// </summary> private void PingEntities() { AwaitAssert(() => { _region2.Tell(1, _probe2.Ref); _probe2.ExpectMsg <int>(1.Seconds()).Should().Be(1); _region2.Tell(2, _probe2.Ref); _probe2.ExpectMsg <int>(1.Seconds()).Should().Be(2); _region2.Tell(3, _probe2.Ref); _probe2.ExpectMsg <int>(1.Seconds()).Should().Be(3); }, TimeSpan.FromSeconds(10)); }
public PersistentViewSpec() : base(Configuration("PersistentViewSpec")) { _prefProbe = CreateTestProbe(); _viewProbe = CreateTestProbe(); _pref = ActorOf(() => new TestPersistentActor(Name, _prefProbe.Ref)); _pref.Tell("a"); _pref.Tell("b"); _prefProbe.ExpectMsg("a-1"); _prefProbe.ExpectMsg("b-2"); }
public void Send6Messages() { // arrange var message = new Wrapper <string>("hello", _testprobe); // act for (var i = 0; i < 20; i++) { _sut.Tell(message); } // assert _testprobe.ExpectMsg("hello"); _testprobe.ExpectNoMsg(); _testprobe.ExpectMsg("hello"); _testprobe.ExpectNoMsg(); _testprobe.ExpectMsg("hello"); _testprobe.ExpectNoMsg(); _testprobe.ExpectMsg("hello"); _testprobe.ExpectNoMsg(); _testprobe.ExpectMsg("hello"); _testprobe.ExpectNoMsg(); _testprobe.ExpectMsg("hello"); _testprobe.ExpectNoMsg(); _testprobe.ExpectMsg("hello"); _testprobe.ExpectNoMsg(); _testprobe.ExpectMsg("hello"); _testprobe.ExpectNoMsg(); }
public void Test1(int repeat, int cutoff) { for (int i = 0; i < repeat; i++) { deliveryManActor.Tell("일반택배발송:" + i); } Within(TimeSpan.FromMilliseconds(cutoff), () => { for (int i = 0; i < repeat; i++) { probe.ExpectMsg <string>(TimeSpan.FromMilliseconds(cutoff)); } }); }
private void RunCoordinatedShutdownWhenDowning() { // coordinator is on Sys2 Cluster.Get(_sys2).Down(Cluster.Get(_sys3).SelfAddress); _probe3.ExpectMsg("CS-unbind-3"); Within(20.Seconds(), () => { AwaitAssert(() => { Cluster.Get(_sys2).State.Members.Count.Should().Be(1); }); }); Within(10.Seconds(), () => { AwaitAssert(() => { Cluster.Get(_sys3).IsTerminated.Should().BeTrue(); _sys3.WhenTerminated.IsCompleted.Should().BeTrue(); }); }); PingEntities(); }
public void SnapshotStore_should_save_and_overwrite_snapshot_with_same_sequence_number_unskipped() { TestProbe _senderProbe = CreateTestProbe(); var md = Metadata[4]; SnapshotStore.Tell(new SaveSnapshot(md, "s-5-modified"), _senderProbe.Ref); var md2 = _senderProbe.ExpectMsg <SaveSnapshotSuccess>().Metadata; Assert.Equal(md.SequenceNr, md2.SequenceNr); SnapshotStore.Tell(new LoadSnapshot(Pid, new SnapshotSelectionCriteria(md.SequenceNr), long.MaxValue), _senderProbe.Ref); var result = _senderProbe.ExpectMsg <LoadSnapshotResult>(); Assert.Equal("s-5-modified", result.Snapshot.Snapshot.ToString()); Assert.Equal(md.SequenceNr, result.Snapshot.Metadata.SequenceNr); // metadata timestamp may have been changed }
private void AwaitMemberUp(TestProbe memberProbe, params RoleName[] nodes) { if (nodes.Length > 1) { RunOn(() => { memberProbe.ExpectMsg <ClusterEvent.MemberUp>(TimeSpan.FromSeconds(15)).Member.Address .Should() .Be(GetAddress(nodes.First())); }, nodes.Skip(1).ToArray()); } RunOn(() => { var roleNodes = nodes.Select(node => GetAddress(node)); var addresses = memberProbe.ReceiveN(nodes.Length, TimeSpan.FromSeconds(15)) .Where(x => x is ClusterEvent.MemberUp) .Select(x => (x as ClusterEvent.MemberUp).Member.Address); addresses.Except(roleNodes).Count().Should().Be(0); }, nodes.First()); EnterBarrier(nodes.First().Name + "-up"); }
public void TestFireAndForget(int expectedTestSec) { var helloActor = Sys.ActorOf(Props.Create(() => new HelloActor("Minsu"))); // 응답 받을 액터를 지정한다. (첫번째:지정자 , 두번째:전송자) helloActor.Tell(probe.Ref, this.TestActor); // 두번째 인자의 Sender(전송장)가 받는 결과값 검사 ExpectMsg("done", TimeSpan.FromSeconds(1)); Within(TimeSpan.FromSeconds(expectedTestSec), () => { helloActor.Tell("hello", this.TestActor); // 지정자가 받는 메시지 검사 probe.ExpectMsg("world", TimeSpan.FromSeconds(1)); // 송신을 하지만 응답을 꼭 알필요없이 Next수행 - fire and foget(군사용어) helloActor.Tell("fire", this.TestActor); helloActor.Tell("fire", this.TestActor); helloActor.Tell("fire", this.TestActor); // 응답메시지가 없음을 검사 probe.ExpectNoMsg(TimeSpan.FromSeconds(1)); }); }
static void Main(string[] args) { TestKit testKit = new TestKit(); ActorSystem actorSystem = testKit.Sys; using (actorSystem) { TestProbe probe = testKit.CreateTestProbe("test-probe"); Action test1 = new Action(() => { // TestKit-based probe which allows sending, reception and reply. IActorRef deviceActor = actorSystem.ActorOf(Device.Props("group", "device")); IActorRef probeRef = probe.Ref; deviceActor.Tell(new RequestTrackDevice("group", "device"), probeRef); probe.ExpectMsg <DeviceRegistered>(); probe.LastSender.Should().Be(deviceActor); Console.WriteLine("Test 1 passed."); }); test1.Invoke(); Action test2 = new Action(() => { // TestKit-based probe which allows sending, reception and reply. var deviceActor = actorSystem.ActorOf(Device.Props("group", "device")); deviceActor.Tell(new RequestTrackDevice("wrongGroup", "device"), probe.Ref); probe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); deviceActor.Tell(new RequestTrackDevice("group", "Wrongdevice"), probe.Ref); probe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); Console.WriteLine("Test 2 passed."); }); test2.Invoke(); Console.WriteLine("UserMessage: App is finished."); // Exit the system after ENTER is pressed Console.ReadLine(); } }
public void ClusterSingletonManager_should_handover_when_oldest_leaves_in_6_node_cluster() { Within(TimeSpan.FromSeconds(30), () => { var leaveNode = _first; RunOn(() => { Cluster.Leave(GetAddress(leaveNode)); }, leaveNode); VerifyRegistration(_second); VerifyMsg(_second, Msg); VerifyProxyMsg(_second, _second, Msg); VerifyProxyMsg(_second, _third, Msg); VerifyProxyMsg(_second, _fourth, Msg); VerifyProxyMsg(_second, _fifth, Msg); VerifyProxyMsg(_second, _sixth, Msg); RunOn(() => { Sys.ActorSelection("/user/consumer").Tell(new Identify("singleton"), _identifyProbe.Ref); _identifyProbe.ExpectMsg <ActorIdentity>(i => { if (i.MessageId.Equals("singleton") && i.Subject != null) { Watch(i.Subject); ExpectTerminated(i.Subject); } }); }, leaveNode); EnterBarrier("after-leave"); }); }
private void RunCoordinatedShutdownWhenLeaving() { Cluster.Get(_sys3).Leave(Cluster.Get(_sys1).SelfAddress); _probe1.ExpectMsg("CS-unbind-1"); Within(20.Seconds(), () => { AwaitAssert(() => { Cluster.Get(_sys2).State.Members.Count.Should().Be(2); Cluster.Get(_sys3).State.Members.Count.Should().Be(2); }); }); Within(10.Seconds(), () => { AwaitAssert(() => { Cluster.Get(_sys1).IsTerminated.Should().BeTrue(); _sys1.WhenTerminated.IsCompleted.Should().BeTrue(); }); }); PingEntities(); }
public void Test1(int cutoffSec, int elemntPerSec) { var throttleWork = Sys.ActorOf(Props.Create(() => new ThrottleWork(elemntPerSec, timeSec))); // 밸브에게 작업자 지정 ( 밸브는 초당 스트림을 모아서 방출한다 ) // 작업자는 방류된 스트림을 기본적으로 쌓아두고, 초당 지정된 개수만 처리한다. throttleActor.Tell(new SetTarget(throttleWork)); // 소비자지정 : 소비자는 몇개가 초당 처리되던 상관없이, 완료된 작업만 제공받는다. throttleWork.Tell(new SetTarget(probe)); Within(TimeSpan.FromSeconds(cutoffSec), () => { // 50개 처리완료는 10초이내에 끝나야함... for (int i = 0; i < 50; i++) { string seq = (i + 1).ToString(); throttleActor.Tell(new Queue(new DelayMsg() { Delay = 0, Seq = seq, Message = $"초당:{elemntPerSec} 테스트-{seq}", State = DelayMsgState.Reserved })); } DelayMsg lastMessage = null; for (int i = 0; i < 50; i++) { lastMessage = probe.ExpectMsg <DelayMsg>(); } //마지막 메시지의 Seq는 50이여야함 Assert.Equal("50", lastMessage.Seq); }); }
public ConnectionDetail EstablishNewClientConnection(bool registerClientHandler = true) { var connectCommander = _spec.CreateTestProbe("connect-commander-probe"); connectCommander.Send(_spec.Sys.Tcp(), new Tcp.Connect(_endpoint, options: ConnectOptions)); connectCommander.ExpectMsg <Tcp.Connected>(); var clientHandler = _spec.CreateTestProbe($"client-handler-probe"); if (registerClientHandler) { connectCommander.Sender.Tell(new Tcp.Register(clientHandler.Ref)); } _bindHandler.ExpectMsg <Tcp.Connected>(); var serverHandler = _spec.CreateTestProbe("server-handler-probe"); _bindHandler.Sender.Tell(new Tcp.Register(serverHandler.Ref)); return(new ConnectionDetail { ClientHandler = clientHandler, ClientConnection = connectCommander.Sender, ServerHandler = serverHandler, ServerConnection = _bindHandler.Sender }); }