public async Task <IHttpActionResult> SetResponse(string uri, string method) { if (uri.StartsWith("/")) { throw new Exception("The URI cannot start with a slash"); } var response = new MockMessage { Content = await Request.Content.ReadAsStringAsync(), ContentType = Request.Content.Headers.ContentType }; var paramsStart = uri.IndexOf("?"); if (paramsStart > -1) { uri = uri.Substring(0, paramsStart); } var key = $"{method}-{uri}"; if (ConfiguredResponses.ContainsKey(key)) { return(this.Conflict()); } ConfiguredResponses.Add(key, response); Requests.Add(key, new List <MockRequest>()); return(this.Ok($"Response configured as {response.ContentType}")); }
/// <summary> /// Sends a response message to the client /// </summary> /// <param name="context">The BizUnit execution context</param> protected override void SendResponse(Context context, MockMessage request, int batchIndex) { if (this.ResponseSelector != null) { context.LogInfo( "Invoking response selector method."); this.ResponsePath = ResponseSelector(request, batchIndex); } // Here we supply the response using (FileStream fs = File.OpenRead(this.ResponsePath)) { context.LogData( string.Format( CultureInfo.CurrentUICulture, "Reading response content from path {0}", this.ResponsePath), fs, true); } var mockMessage = new MockMessage(this.ResponsePath, this.encoding); System.Diagnostics.Debug.WriteLine( "Sending response to the mocked endpoint", "TransMock.Integration.BizUnit.MockRequestResponseStep"); this.pipeServer.WriteMessage(this.connectionId, mockMessage); context.LogInfo("Done sending the response"); }
/// <summary> /// Sends a request to the server endpoint /// </summary> /// <param name="context">The execution context for the step</param> protected virtual void SendRequest(Context context) { using (FileStream fs = File.OpenRead(this.RequestPath)) { context.LogData( string.Format( CultureInfo.CurrentUICulture, "Reading request content from path {0}", this.RequestPath), fs, true); } System.Diagnostics.Debug.WriteLine( "Sending request to the pipe server", "TransMock.Integration.BizUnit.MockSendStep"); var mockMessage = new MockMessage(this.RequestPath, this.encoding); mockMessage.Properties = this.MessageProperties; this.pipeClient.WriteMessage(mockMessage); System.Diagnostics.Debug.WriteLine( "Request sent to the pipe server", "TransMock.Integration.BizUnit.MockSendStep"); }
public void TestOneWayReceive_XML() { string xml = "<SomeTestMessage><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessage>"; string receivedXml = null; pipeServer.ReadCompleted += (o, readArgs) => { receivedXml = readArgs.Message.Body; syncEvent.Set(); }; using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "TestPipeServer", PipeDirection.InOut, PipeOptions.Asynchronous)) { var mockMessage = new MockMessage(); mockMessage.Body = xml; using (MemoryStream msgStream = new MemoryStream()) { var formatter = new BinaryFormatter(); pipeClient.Connect(10000); formatter.Serialize(msgStream, mockMessage); WriteMockMessage(pipeClient, msgStream); pipeClient.WaitForPipeDrain(); } } //Now we read the message in the inbound handler syncEvent.Wait(TimeSpan.FromSeconds(10)); Assert.IsNotNull(receivedXml, "Message was not received by the server"); Assert.AreEqual(xml, receivedXml, "Contents of received message is different"); }
/// <summary> /// Sends a message through the server instance /// </summary> /// <param name="connectionId">The connection id to which the message shall be sent to</param> /// <param name="mockMessage">The message contents that shall be sent</param> /// <returns></returns> public async Task SendServerMessageAsync(int connectionId, MockMessage mockMessage) { await Task.Factory.StartNew(() => MockMessageServer .WriteMessage(connectionId, mockMessage) ); }
/// <summary> /// Sends a message through the client instance /// </summary> /// <param name="mockMessage">The message that shall be sent through the client</param> /// <returns></returns> public async Task SendClientMessageAsync(MockMessage mockMessage) { await Task.Factory.StartNew(() => MockMessageClient .WriteMessage(mockMessage) ); }
public void Setup() { _bus = new MessageBus(); _messOneTriggerCount = _messTwoTriggerCount = 0; _mockOneTriggerCount = _mockTwoTriggerCount = 0; _receivedMock = null; _receivedMessage = null; }
public void TestSaludar() { MockMessage message = new MockMessage(); Person personTest = new Person(message); personTest.greet(); Assert.IsTrue(message.isEmittedMessage); }
public static void Establish(SearchItemOfType type) { var query = Pleasure.Generator.Invent <GetImageQuery>(dsl => dsl.Tuning(r => r.Type, type)); expected = Pleasure.Generator.Bytes(); mockQuery = MockQuery <GetImageQuery, byte[]> .When(query); }
private MockMessage PrepareMockMessage(System.ServiceModel.Channels.Message message) { byte[] msgBuffer = null; if (!message.IsFault) { // Handling regular content messages System.Diagnostics.Debug.WriteLine( "Handling content response message", "TransMock.Wcf.Adapter.MockAdapterInboundReply"); XmlDictionaryReader xdr = message.GetReaderAtBodyContents(); // Read the start element and extract its contents as a base64 encoded bytes if (xdr.NodeType == XmlNodeType.Element) { // in case the content is nested in an element under the Body element xdr.Read(); } msgBuffer = xdr.ReadContentAsBase64(); } else { // Handling faults returned by BizTalk System.Diagnostics.Debug.WriteLine( "Handling fault response message", "TransMock.Wcf.Adapter.MockAdapterInboundReply"); using (var messageBuffer = message.CreateBufferedCopy(1024 ^ 3)) // Allowing for buffer of 1 GB { using (var msgStream = new System.IO.MemoryStream(4096)) { messageBuffer.WriteMessage(msgStream); msgBuffer = Convert.FromBase64String( Convert.ToBase64String(msgStream.ToArray())); } } } if (msgBuffer.Length == 0) { // Message is with empty body, simply return System.Diagnostics.Debug.WriteLine( "Response message has empty body. Exiting.", "TransMock.Wcf.Adapter.MockAdapterInboundReply"); return(null); } // Create MockMessage intance var mockMessage = new MockMessage( msgBuffer, this.encoding); return(mockMessage); }
/// <summary> /// Copies the promoted properties from the BizTalk message to the mock message /// </summary> /// <param name="message">The message from where the properties will be copied</param> /// <param name="mockMessage">The mock message to where the properties will be copied</param> private static void CopyPromotedProperties(Message message, MockMessage mockMessage) { foreach (var property in message.Properties) { System.Diagnostics.Debug.WriteLine( "Property name:{0}, value:{1}", property.Key, property.Value ?? property.Value.ToString()); try { // Lookup the namespace prefix string[] propertyParts = property.Key.Split('#'); if (propertyParts.Length == 2) { var utilsType = typeof(Utils.BizTalkProperties.Namespaces); var reflectedProperty = utilsType.GetProperties() .Where( p => p.PropertyType == typeof(string) && p.GetValue(null, null).ToString() == propertyParts[0]) .SingleOrDefault(); if (reflectedProperty != null) { // Adding the adapter propertiy to the mock message instance mockMessage.Properties.Add( string.Format( "{0}.{1}", reflectedProperty.Name, propertyParts[1]), property.Value == null ? string.Empty : property.Value.ToString() ); } else { // No adapter property match found // Adding custom property to the list of properties mockMessage.Properties.Add( property.Key, (string)property.Value); } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine( string.Format( "Property {0} not copied to mock message. Exception: {1}", property.Key, ex.Message), "TransMock.Wcf.Adapter.MockAdapterOutboundHandler"); } } }
public static void SendResponse(OutboundTestHelper testHelper) { // Sending a response if (!string.IsNullOrEmpty(testHelper.responseXml)) { var responseMessage = new MockMessage() { Body = testHelper.responseXml }; using (var msgStream = new MemoryStream(4096)) { var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(msgStream, responseMessage); msgStream.Seek(0, SeekOrigin.Begin); //We write the response content back and flush it down the drain. testHelper.pipeServer.Write(msgStream.ToArray(), 0, (int)msgStream.Length); } } else if (!string.IsNullOrEmpty(testHelper.responsePath)) { var responseMessage = new MockMessage(testHelper.responsePath, testHelper.responseEncoding); using (var msgStream = new MemoryStream(4096)) { var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(msgStream, responseMessage); msgStream.Seek(0, SeekOrigin.Begin); int byteCountRead = 0; byte[] outBuffer = new byte[4096]; //Streaming respoonse from file while ((byteCountRead = msgStream.Read(outBuffer, 0, outBuffer.Length)) > 0) { testHelper.pipeServer.Write(outBuffer, 0, byteCountRead); } } } else { throw new InvalidOperationException("There was no response content defined"); } // Writing the EndOfMessage sequence to the end of stream testHelper.pipeServer.Write( OutboundTestHelper.EndOfMessage, 0, OutboundTestHelper.EndOfMessage.Length); testHelper.pipeServer.Flush(); testHelper.pipeServer.WaitForPipeDrain(); }
public void TestOneWay_XML() { PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule( new PipeAccessRule( "USERS", PipeAccessRights.CreateNewInstance | PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); // We first spin a pipe server to make sure that the send port will be able to connect using (NamedPipeServerStream pipeServer = new NamedPipeServerStream( "OneWaySend", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps)) { string xml = "<SomeTestMessage><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessage>"; OutboundTestHelper testHelper = new OutboundTestHelper(pipeServer); pipeServer.BeginWaitForConnection(cb => testHelper.ClientConnected(cb), testHelper); //Here we spin the pipe client that will send the message to BizTalk using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "OneWayReceive", PipeDirection.InOut, PipeOptions.Asynchronous)) { var mockMessage = new MockMessage(); mockMessage.Body = xml; using (var memStream = new MemoryStream()) { var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(memStream, mockMessage); pipeClient.Connect(10000); pipeClient.Write(memStream.ToArray(), 0, (int)memStream.Length); pipeClient.WriteByte(0x00); pipeClient.WaitForPipeDrain(); } } //Here we wait for the event to be signalled testHelper.syncEvent.WaitOne(60000); //The event was signalled, we get the message stirng from the outBuffer var receivedMsg = TestUtils.ConvertToMockMessage(testHelper.memStream); Assert.AreEqual(xml, receivedMsg.Body, "Contents of the received message is different"); Assert.IsTrue(receivedMsg.Properties.Count > 1, "Received message does not contain properties"); Assert.IsTrue(receivedMsg.Properties.ContainsKey( "http://schemas.microsoft.com/BizTalk/2003/system-properties#BizTalkMessageID"), "Received message does not contain MessageID property"); } }
public void TestEmptyAddress() { var incomingMessage = new MockMessage(); var node = new MockNode(1); incomingMessage.SetIncoming(node, string.Join(":", "%%>message", "234479208", UnixTimestamp, "call.route", "id=sip/852978", "module=sip", "status=incoming", "address=", "billid=1418778188-76", "answered=false", "direction=incoming", "caller=00012521339915", "called=", "callername=00012521339915")); Dispatcher.Process(incomingMessage).Wait(); var result = node.RetrieveMessage(); var routingTree = getRoutingTree(node, "1418778188-76", false); var routingTree1 = getRoutingTree(node, "1418778188-76", true); var routingTree2 = getRoutingTree(node, "1418778188-76", false); var routingTree3 = getRoutingTree(node, "1418778188-76", true); // Assert - split because MS are measured for 'clwaitingtime,clprocessingtime' and change between runs Assert.IsTrue(result.OutgoingMessage.StartsWith("%%<message:234479208:true:call.route::error=403:reason=:" + "clnodeid=1:clcustomerid=:clcustomeripid=:cltrackingid=1418778188-76:clprocessingtime=")); Assert.IsTrue(result.OutgoingMessage.Contains(":clcustomerpriceid=:clcustomerpricepermin=:clcustomercurrency=:cldialcodemasterid=:clwaitingtime=")); Assert.IsTrue(result.OutgoingMessage.EndsWith(CopyParams + "\n")); Assert.IsNotNull(routingTree); Assert.AreEqual(routingTree.Context.Endpoint, Utilities.RoutingTree.TargetType.Context); Assert.IsNull(routingTree.Context.Id); Assert.IsNull(routingTree.Context.InternalRoutedGateway); Assert.AreEqual(routingTree.Context.LCRGateways.Count, 0); Assert.IsNull(routingTree.Context.Route); Assert.AreEqual(routingTree.Context.RoutingAction, Utilities.RoutingTree.ContextAction.Cancelled); Assert.AreEqual(routingTree.Context.TargetReason, Utilities.RoutingTree.Reason.AddressIsEmpty); // test removing Assert.IsNotNull(routingTree1); Assert.AreSame(routingTree, routingTree1); Assert.IsNull(routingTree2); Assert.IsNull(routingTree3); }
public void CreateMessage_GivenValidPacket_ReturnsTrue() { //arrange MockMessage mockMessage = new MockMessage(); var packet = new Packet(); string testPayload = "Test Message|A3C6B524-1BE1-4D9D-84FB-EF64993CCA28|97846D61-1CA0-49BD-8E79-AE3AF6373B26"; packet.buffer = Encoding.ASCII.GetBytes(testPayload); //act packet.CreateMessage(); //assert Assert.IsTrue(mockMessage.Equals(packet.message)); }
public override async Task <Message> HandleMessage(Message sourceMessage) { // Get count var count = ((MockMessage <string>)sourceMessage).Value.Length; // Notify subscribers messageHandledProducer.ProduceEvent(count); // Call next handler var sinkMessage = new MockMessage <int>(count); return(await base.HandleMessage(sinkMessage)); }
private bool ValidateOutMessage(MockMessage message) { Assert.IsTrue( message.Properties.Count > 0, "The number of properties in the received message is not as expected"); Assert.AreEqual( "mockBinding", message.Properties["WCF.BindingType"], "The WCF.BindingName property is incorrect!"); return(true); }
public override async Task <Message> HandleMessage(Message sourceMessage) { // Transform message var message = ((MockMessage <string>)sourceMessage).Value.ToLower(); // Notify subscribers messageHandledProducer.ProduceEvent(message); // Call next handler var sinkMessage = new MockMessage <string>(message); return(await base.HandleMessage(sinkMessage)); }
/// <summary> /// Reads the contents of the file provided in the FilePath property and returns an instance /// of the <see cref="MockMessage" /> class initialized with this contents /// </summary> /// <param name="requestIndex">The index of the request in a multi-request scenario</param> /// <param name="requestMessage">The request message</param> /// <returns>An instance of <see cref="MockMessage" /> class with contents taken from the file specified in the FilePath property</returns> public override MockMessage SelectResponseMessage(int requestIndex, MockMessage requestMessage) { if (this.FilePath == null) { throw new InvalidOperationException("No file path specified for fetching the response contents!"); } var mockResponse = new MockMessage( this.FilePath, requestMessage.Encoding); return(mockResponse); }
/// <summary> /// Performs serial validation of a message that has been received by the step /// </summary> /// <param name="message">The message object that will be validated</param> /// <param name="context">The BizUnit context isntance</param> private void SerialValidation(MockMessage message, Context context) { foreach (var step in this.SubSteps) { if (step is LambdaValidationStep) { ((LambdaValidationStep)step).Execute(message, context); } else { step.Execute(message.BodyStream, context); } } }
public void MultipleSubscriberTypes() { var message = new MockMessage(); _bus.Subscribe<Message>(OnMessageOne); _bus.Subscribe<Message>(OnMessageTwo); _bus.Subscribe<MockMessage>(OnMockOne); _bus.Subscribe<MockMessage>(OnMockTwo); _bus.Broadcast(message); Assert.AreEqual(0, _messOneTriggerCount, "No messages for different subscriber type"); Assert.AreEqual(0, _messTwoTriggerCount, "No messages for different subscriber type"); Assert.AreEqual(1, _mockOneTriggerCount, "Subscriber for MockMessage should get triggered"); Assert.AreEqual(1, _mockTwoTriggerCount, "Subscriber for MockMessage should get triggered"); Assert.AreEqual(message, _receivedMock, "Same message reference should have been passed"); }
public void TestOneWayReceive_MockMessage_FlatFile_ASCII() { string ffContent = "303330123333777;ABCD;00001;00002;2014-01-15;21:21:33.444;EFGH;"; MockMessage receivedMessage = null; pipeServer.ReadCompleted += (o, readArgs) => { receivedMessage = readArgs.Message; syncEvent.Set(); }; using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "TestPipeServer", PipeDirection.InOut, PipeOptions.Asynchronous)) { var mockMessage = new MockMessage(Encoding.ASCII); mockMessage.Body = ffContent; mockMessage.Properties.Add("SomeProperty1", "TestVal1"); mockMessage.Properties.Add("SomeProperty2", "TestVal2"); mockMessage.Properties.Add("SomeProperty3", "TestVal3"); using (MemoryStream msgStream = new MemoryStream()) { var formatter = new BinaryFormatter(); pipeClient.Connect(10000); formatter.Serialize(msgStream, mockMessage); pipeClient.Write(msgStream.ToArray(), 0, (int)msgStream.Length); // pipeClient.WriteByte(0x00);// Write the EOF byte pipeClient.WaitForPipeDrain(); } pipeClient.Close(); } //Now we read the message in the inbound handler syncEvent.Wait(TimeSpan.FromSeconds(10)); Assert.IsNotNull(receivedMessage, "Message was not received by the server"); Assert.AreEqual(ffContent, receivedMessage.Body, "Contents of received message is different"); Assert.AreEqual(3, receivedMessage.Properties.Count, "Number of properties in received message is different"); Assert.AreEqual("TestVal1", receivedMessage.Properties["SomeProperty1"], "Value of property 1 is different"); Assert.AreEqual("TestVal2", receivedMessage.Properties["SomeProperty2"], "Value of property 1 is different"); Assert.AreEqual("TestVal3", receivedMessage.Properties["SomeProperty3"], "Value of property 1 is different"); }
/// <summary> /// Selects the response message from the provided request message and its zero based reception index /// </summary> /// <param name="requestIndex">Zero base index indicating the order of reception of the message</param> /// <param name="requestMessage">The actual request message</param> /// <returns></returns> public override MockMessage SelectResponseMessage(int requestIndex, MockMessage requestMessage) { if (requestIndex < FilePaths.Count()) { var mockResponse = new MockMessage( FilePaths.ElementAt(requestIndex), requestMessage.Encoding); return(mockResponse); } else { throw new IndexOutOfRangeException("Provided message index exceeds the number of FilePaths configured"); } }
/// <summary> /// Executes the validation logic of the step against an instance of MockMessage class. /// </summary> /// <param name="message">The instance of the mock message</param> /// <param name="context">The BizUnit context</param> public void Execute(MockMessage message, Context context) { if (MessageValidationCallback == null) { Execute(message.BodyStream, context); } else { bool result = MessageValidationCallback(message); if (!result) { throw new ValidationStepExecutionException("Validation in a lambda expression failed!", context.TestName); } } }
public void TestOneWayReceive_MockMessage_XML_Unicode_Base64() { string xml = "<SomeTestMessage><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessage>"; string receivedXml = null; pipeServer.ReadCompleted += (o, readArgs) => { receivedXml = readArgs.Message.BodyBase64; syncEvent.Set(); }; using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "TestPipeServer", PipeDirection.InOut, PipeOptions.Asynchronous)) { var mockMessage = new MockMessage() { Encoding = Encoding.Unicode }; mockMessage.Body = xml; using (MemoryStream msgStream = new MemoryStream()) { var formatter = new BinaryFormatter(); pipeClient.Connect(10000); formatter.Serialize(msgStream, mockMessage); pipeClient.Write(msgStream.ToArray(), 0, (int)msgStream.Length); // pipeClient.WriteByte(0x00);// Write the EOF byte pipeClient.WaitForPipeDrain(); } pipeClient.Close(); } //Now we read the message in the inbound handler syncEvent.Wait(TimeSpan.FromSeconds(10)); string xmlBase64 = Convert.ToBase64String( Encoding.Unicode.GetBytes(xml)); Assert.IsNotNull(receivedXml, "Message was not received by the server"); Assert.AreEqual(xmlBase64, receivedXml, "Contents of received message is different"); }
public void TestOneWay_FlatFile() { PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule("USERS", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); //We first spin a pipe server to make sure that the send port will be able to connect using (NamedPipeServerStream pipeServer = new NamedPipeServerStream( "OneWaySend", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps)) { string ffContent = "303330123333777;ABCD;00001;00002;2014-01-15;21:21:33.444;EFGH;"; OutboundTestHelper testHelper = new OutboundTestHelper(pipeServer); pipeServer.BeginWaitForConnection(cb => testHelper.ClientConnected(cb), testHelper); //Here we spin the pipe client that will send the message to BizTalk using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "OneWayReceive", PipeDirection.InOut, PipeOptions.Asynchronous)) { var mockMessage = new MockMessage(); mockMessage.Body = ffContent; using (var memStream = new MemoryStream()) { var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(memStream, mockMessage); pipeClient.Connect(10000); pipeClient.Write(memStream.ToArray(), 0, (int)memStream.Length); pipeClient.WriteByte(0x00); pipeClient.WaitForPipeDrain(); } } //Here we wait for the event to be signalled testHelper.syncEvent.WaitOne(60000); //The event was signalled, we get the message stirng from the outBuffer var receivedMsg = TestUtils.ConvertToMockMessage(testHelper.memStream); Assert.AreEqual(ffContent, receivedMsg.Body, "Contents of the received message is different"); } }
public void TestOneWayReceive_FlatFile_Unicode() { string ffContent = "303330123333777;ABCD;00001;00002;2014-01-15;21:21:33.444;EFGH;"; string receivedContent = null; pipeServer.ReadCompleted += (o, readArgs) => { receivedContent = readArgs.Message.Body; syncEvent.Set(); }; using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "TestPipeServer", PipeDirection.InOut, PipeOptions.Asynchronous)) { var mockMessage = new MockMessage() { Encoding = Encoding.Unicode }; mockMessage.Body = ffContent; using (MemoryStream msgStream = new MemoryStream()) { var formatter = new BinaryFormatter(); pipeClient.Connect(10000); formatter.Serialize(msgStream, mockMessage); pipeClient.Write(msgStream.ToArray(), 0, (int)msgStream.Length); // pipeClient.Flush(); pipeClient.WaitForPipeDrain(); } pipeClient.Close(); } //Now we read the message in the inbound handler syncEvent.Wait(TimeSpan.FromSeconds(10)); Assert.IsNotNull(receivedContent, "Message was not received by the server"); Assert.AreEqual(ffContent, receivedContent, "Contents of received message is different"); }
public async Task KafkaActivity_ProduceConsumeMessage_CorrectActivityReceived() { // Arrange var baggageKey = "testKey"; _activityContextAccessor.CurrentActivity.AddBaggage(baggageKey, "testing"); var mockMessage = new MockMessage(); var messageId = Guid.NewGuid().ToString(); var message = new KafkaMessage <string, MockMessage> { Key = "mock-message", Value = mockMessage, MessageId = messageId, MessageType = "mockMessage.Created" }; var cts = new CancellationTokenSource(); var consumedMessage = new KafkaMessage <string, MockMessage>(); // Act #pragma warning disable 4014 Task.Factory.StartNew(() => #pragma warning restore 4014 { while (!cts.IsCancellationRequested) { consumedMessage = (KafkaMessage <string, MockMessage>)_kafkaConsumer.Consume(cts.Token); _semaphore.Release(); } }, TaskCreationOptions.LongRunning); await _kafkaProducer.ProduceAsync(message); await _semaphore.WaitAsync(30000); // Assert Assert.NotEmpty(consumedMessage.Headers[Constants.CorrelationIdHeaderName]); Assert.NotEmpty(consumedMessage.Headers[baggageKey]); }
/// <summary> /// Receives a response message from the server /// </summary> /// <param name="context">The BizUnit execution context</param> protected override void ReceiveResponse(Context context) { context.LogInfo("Waiting to read the response from the endpoint"); System.Diagnostics.Trace.WriteLine( "Reading the response from the endpoint", "TransMock.Integration.BizUnit.MockSolicitResponseStep"); context.LogInfo("Reading the response from the endpoint"); this.responseMessage = this.pipeClient.ReadMessage(); System.Diagnostics.Debug.WriteLine( "Response read!", "TransMock.Integration.BizUnit.MockSolicitResponseStep"); context.LogData( "The response received from the mocked endpoint is:", this.responseMessage.BodyStream, true); }
public void TestEngineTimer() { var node = new MockNode(1); var incomingMessage = new MockMessage(); incomingMessage.SetIncoming(node, string.Join(":", "%%>message", "051EFE60.1969150591", UnixTimestamp.ToString(), "engine.timer", "", "time=1468577974", "nodename=WIN-E2OH1TVPT5C" )); Dispatcher.Process(incomingMessage).Wait(); var result = node.RetrieveMessage(); // Assert - split because MS are measured for 'clwaitingtime,clprocessingtime' and change between runs Assert.AreEqual <string>(result.OutgoingMessage, "%%<message:051EFE60.1969150591:false:engine.timer::time=1468577974\n"); }
/// <summary> /// Performs cascading validation of a message that has been received by the step /// </summary> /// <param name="message">The message object that will be validated</param> /// <param name="context">The BizUnit context isntance</param> /// <param name="index">The index at which to extract the collection of validation sub steps</param> private void CascadingValidation(MockMessage message, Context context, int index) { if (this.CascadingSubSteps.Count > 0) { var validationSubSteps = this.CascadingSubSteps[index]; if (validationSubSteps != null) { foreach (var step in validationSubSteps) { if (step is LambdaValidationStep) { ((LambdaValidationStep)step).Execute(message, context); } else { step.Execute(message.BodyStream, context); } } } } }
public void TestOneWayReceive_MockMessage_XML_FromFile() { string xml = File.ReadAllText("StartMessage.xml"); string receivedXml = null; pipeServer.ReadCompleted += (o, readArgs) => { receivedXml = readArgs.Message.Body; syncEvent.Set(); }; using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "TestPipeServer", PipeDirection.InOut, PipeOptions.Asynchronous)) { var mockMessage = new MockMessage("StartMessage.xml", Encoding.UTF8); using (MemoryStream msgStream = new MemoryStream()) { var formatter = new BinaryFormatter(); pipeClient.Connect(10000); formatter.Serialize(msgStream, mockMessage); WriteMockMessage(pipeClient, msgStream); pipeClient.WaitForPipeDrain(); } pipeClient.Close(); } //Now we read the message in the inbound handler syncEvent.Wait(TimeSpan.FromSeconds(10)); Assert.IsNotNull(receivedXml, "Message was not received by the server"); Assert.AreEqual(xml, receivedXml.Trim('\u0000'), "Contents of received message is different"); }
private void OnMockOne(MockMessage m) { _mockOneTriggerCount++; _receivedMock = m; }
private void OnMockTwo(MockMessage m) { _mockTwoTriggerCount++; }