http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/MapMessageTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/MapMessageTest.cs b/src/test/csharp/MapMessageTest.cs new file mode 100644 index 0000000..f904c97 --- /dev/null +++ b/src/test/csharp/MapMessageTest.cs @@ -0,0 +1,208 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using System.Collections; +using Apache.NMS.Util; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + //[TestFixture] + public class MapMessageTest : NMSTest + { + protected bool a = true; + protected byte b = 123; + protected char c = 'c'; + protected short d = 0x1234; + protected int e = 0x12345678; + protected long f = 0x1234567812345678; + protected string g = "Hello World!"; + protected bool h = false; + protected byte i = 0xFF; + protected short j = -0x1234; + protected int k = -0x12345678; + protected long l = -0x1234567812345678; + protected float m = 2.1F; + protected double n = 2.3; + protected byte[] o = {1, 2, 3, 4, 5}; + + protected MapMessageTest(NMSTestSupport testSupport) + : base(testSupport) + { + } + + //[Test] + public virtual void TestSendReceiveMapMessage( + //[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] + MsgDeliveryMode deliveryMode, string testDestRef) + { + using(IConnection connection = CreateConnection(GetTestClientId())) + { + connection.Start(); + using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) + { + IDestination destination = GetClearDestinationByNodeReference(session, testDestRef); + using(IMessageConsumer consumer = session.CreateConsumer(destination)) + using(IMessageProducer producer = session.CreateProducer(destination)) + { + producer.DeliveryMode = deliveryMode; + IMapMessage request = session.CreateMapMessage(); + request.Body["a"] = a; + request.Body["b"] = b; + request.Body["c"] = c; + request.Body["d"] = d; + request.Body["e"] = e; + request.Body["f"] = f; + request.Body["g"] = g; + request.Body["h"] = h; + request.Body["i"] = i; + request.Body["j"] = j; + request.Body["k"] = k; + request.Body["l"] = l; + request.Body["m"] = m; + request.Body["n"] = n; + request.Body["o"] = o; + producer.Send(request); + + IMapMessage message = consumer.Receive(receiveTimeout) as IMapMessage; + Assert.IsNotNull(message, "No message returned!"); + Assert.AreEqual(request.Body.Count, message.Body.Count, "Invalid number of message maps."); + Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); + Assert.AreEqual(ToHex(f), ToHex(message.Body.GetLong("f")), "map entry: f as hex"); + + // use generic API to access entries + Assert.AreEqual(a, message.Body["a"], "generic map entry: a"); + Assert.AreEqual(b, message.Body["b"], "generic map entry: b"); + Assert.AreEqual(c, message.Body["c"], "generic map entry: c"); + Assert.AreEqual(d, message.Body["d"], "generic map entry: d"); + Assert.AreEqual(e, message.Body["e"], "generic map entry: e"); + Assert.AreEqual(f, message.Body["f"], "generic map entry: f"); + Assert.AreEqual(g, message.Body["g"], "generic map entry: g"); + Assert.AreEqual(h, message.Body["h"], "generic map entry: h"); + Assert.AreEqual(i, message.Body["i"], "generic map entry: i"); + Assert.AreEqual(j, message.Body["j"], "generic map entry: j"); + Assert.AreEqual(k, message.Body["k"], "generic map entry: k"); + Assert.AreEqual(l, message.Body["l"], "generic map entry: l"); + Assert.AreEqual(m, message.Body["m"], "generic map entry: m"); + Assert.AreEqual(n, message.Body["n"], "generic map entry: n"); + Assert.AreEqual(o, message.Body["o"], "generic map entry: o"); + + // use type safe APIs + Assert.AreEqual(a, message.Body.GetBool("a"), "map entry: a"); + Assert.AreEqual(b, message.Body.GetByte("b"), "map entry: b"); + Assert.AreEqual(c, message.Body.GetChar("c"), "map entry: c"); + Assert.AreEqual(d, message.Body.GetShort("d"), "map entry: d"); + Assert.AreEqual(e, message.Body.GetInt("e"), "map entry: e"); + Assert.AreEqual(f, message.Body.GetLong("f"), "map entry: f"); + Assert.AreEqual(g, message.Body.GetString("g"), "map entry: g"); + Assert.AreEqual(h, message.Body.GetBool("h"), "map entry: h"); + Assert.AreEqual(i, message.Body.GetByte("i"), "map entry: i"); + Assert.AreEqual(j, message.Body.GetShort("j"), "map entry: j"); + Assert.AreEqual(k, message.Body.GetInt("k"), "map entry: k"); + Assert.AreEqual(l, message.Body.GetLong("l"), "map entry: l"); + Assert.AreEqual(m, message.Body.GetFloat("m"), "map entry: m"); + Assert.AreEqual(n, message.Body.GetDouble("n"), "map entry: n"); + Assert.AreEqual(o, message.Body.GetBytes("o"), "map entry: o"); + } + } + } + } + + //[Test] + public virtual void TestSendReceiveNestedMapMessage( + //[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] + MsgDeliveryMode deliveryMode, string testDestRef) + { + using(IConnection connection = CreateConnection(GetTestClientId())) + { + connection.Start(); + using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) + { + IDestination destination = GetClearDestinationByNodeReference(session, testDestRef); + using(IMessageConsumer consumer = session.CreateConsumer(destination)) + using(IMessageProducer producer = session.CreateProducer(destination)) + { + try + { + producer.DeliveryMode = deliveryMode; + IMapMessage request = session.CreateMapMessage(); + const string textFieldValue = "Nested Map Messages Rule!"; + + request.Body.SetString("textField", textFieldValue); + + IDictionary grandChildMap = new Hashtable(); + grandChildMap["x"] = "abc"; + grandChildMap["y"] = new ArrayList(new object[] { "a", "b", "c" }); + + IDictionary nestedMap = new Hashtable(); + nestedMap["a"] = "foo"; + nestedMap["b"] = (int) 23; + nestedMap["c"] = (long) 45; + nestedMap["d"] = grandChildMap; + + request.Body.SetDictionary("mapField", nestedMap); + request.Body.SetList("listField", new ArrayList(new Object[] { "a", "b", "c" })); + + producer.Send(request); + + IMapMessage message = consumer.Receive(receiveTimeout) as IMapMessage; + Assert.IsNotNull(message, "No message returned!"); + Assert.AreEqual(request.Body.Count, message.Body.Count, "Invalid number of message maps."); + Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); + + string textFieldResponse = message.Body.GetString("textField"); + Assert.AreEqual(textFieldValue, textFieldResponse, "textField does not match."); + + IDictionary nestedMapResponse = message.Body.GetDictionary("mapField"); + Assert.IsNotNull(nestedMapResponse, "Nested map not returned."); + Assert.AreEqual(nestedMap.Count, nestedMapResponse.Count, "nestedMap: Wrong number of elements"); + Assert.AreEqual("foo", nestedMapResponse["a"], "nestedMap: a"); + Assert.AreEqual(23, nestedMapResponse["b"], "nestedMap: b"); + Assert.AreEqual(45, nestedMapResponse["c"], "nestedMap: c"); + + IDictionary grandChildMapResponse = nestedMapResponse["d"] as IDictionary; + Assert.IsNotNull(grandChildMapResponse, "Grand child map not returned."); + Assert.AreEqual(grandChildMap.Count, grandChildMapResponse.Count, "grandChildMap: Wrong number of elements"); + Assert.AreEqual(grandChildMapResponse["x"], "abc", "grandChildMap: x"); + + IList grandChildList = grandChildMapResponse["y"] as IList; + Assert.IsNotNull(grandChildList, "Grand child list not returned."); + Assert.AreEqual(3, grandChildList.Count, "grandChildList: Wrong number of list elements."); + Assert.AreEqual("a", grandChildList[0], "grandChildList: a"); + Assert.AreEqual("b", grandChildList[1], "grandChildList: b"); + Assert.AreEqual("c", grandChildList[2], "grandChildList: c"); + + IList listFieldResponse = message.Body.GetList("listField"); + Assert.IsNotNull(listFieldResponse, "Nested list not returned."); + Assert.AreEqual(3, listFieldResponse.Count, "listFieldResponse: Wrong number of list elements."); + Assert.AreEqual("a", listFieldResponse[0], "listFieldResponse: a"); + Assert.AreEqual("b", listFieldResponse[1], "listFieldResponse: b"); + Assert.AreEqual("c", listFieldResponse[2], "listFieldResponse: c"); + } + catch(NotSupportedException) + { + } + catch(NMSException e) + { + Assert.IsTrue(e.InnerException.GetType() == typeof(NotSupportedException)); + } + } + } + } + } + } +}
http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/MessageSelectorTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/MessageSelectorTest.cs b/src/test/csharp/MessageSelectorTest.cs new file mode 100644 index 0000000..413a965 --- /dev/null +++ b/src/test/csharp/MessageSelectorTest.cs @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using System.Threading; +using Apache.NMS.Util; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + //[TestFixture] + //[Category("LongRunning")] + public class MessageSelectorTest : NMSTest + { + private int receivedNonIgnoredMsgCount = 0; + private int receivedIgnoredMsgCount = 0; + private bool simulateSlowConsumer = false; + + protected MessageSelectorTest(NMSTestSupport testSupport) + : base(testSupport) + { + } + + //[Test] + public virtual void TestFilterIgnoredMessages( + //[Values(SELECTOR_TEST_QUEUE, SELECTOR_TEST_TOPIC)] + string testDestRef) + { + simulateSlowConsumer = false; + RunFilterIgnoredMessagesTest(testDestRef); + } + + /// <summary> + /// A slow consumer will trigger the producer flow control on the broker when the destination is + /// a queue. It will also trigger the consumer flow control by slowing down the feed to all of the + /// consumers on the queue to only send messages as fast as the slowest consumer can run. + /// When sending to a topic, the producer will not be slowed down, and consumers will be allowed + /// to run as fast as they can go. + /// Since this test can take a long time to run, it is marked as explicit. + /// </summary> + /// <param name="testDestRef"></param> + //[Test] + public virtual void TestFilterIgnoredMessagesSlowConsumer( + //[Values(SELECTOR_TEST_QUEUE, SELECTOR_TEST_TOPIC)] + string testDestRef) + { + simulateSlowConsumer = true; + RunFilterIgnoredMessagesTest(testDestRef); + } + + public void RunFilterIgnoredMessagesTest(string testDestRef) + { + TimeSpan ttl = TimeSpan.FromMinutes(30); + const int MaxNumRequests = 100000; + + using(IConnection connection1 = CreateConnection(GetTestClientId())) + using(IConnection connection2 = CreateConnection(GetTestClientId())) + using(IConnection connection3 = CreateConnection(GetTestClientId())) + { + connection1.Start(); + connection2.Start(); + connection3.Start(); + using(ISession session1 = connection1.CreateSession(AcknowledgementMode.AutoAcknowledge)) + using(ISession session2 = connection2.CreateSession(AcknowledgementMode.AutoAcknowledge)) + using(ISession session3 = connection3.CreateSession(AcknowledgementMode.AutoAcknowledge)) + { + IDestination destination1 = GetClearDestinationByNodeReference(session1, testDestRef); + IDestination destination2 = GetClearDestinationByNodeReference(session2, testDestRef); + IDestination destination3 = GetClearDestinationByNodeReference(session3, testDestRef); + + using(IMessageProducer producer = session1.CreateProducer(destination1)) + using(IMessageConsumer consumer1 = session2.CreateConsumer(destination2, "JMSType NOT LIKE '%IGNORE'")) + { + int numNonIgnoredMsgsSent = 0; + int numIgnoredMsgsSent = 0; + + producer.DeliveryMode = MsgDeliveryMode.NonPersistent; + + receivedNonIgnoredMsgCount = 0; + receivedIgnoredMsgCount = 0; + consumer1.Listener += new MessageListener(OnNonIgnoredMessage); + IMessageConsumer consumer2 = null; + + for(int index = 1; index <= MaxNumRequests; index++) + { + IMessage request = session1.CreateTextMessage(String.Format("Hello World! [{0} of {1}]", index, MaxNumRequests)); + + request.NMSTimeToLive = ttl; + if(0 == (index % 2)) + { + request.NMSType = "ACTIVE"; + numNonIgnoredMsgsSent++; + } + else + { + request.NMSType = "ACTIVE.IGNORE"; + numIgnoredMsgsSent++; + } + +if(index % 200 == 0) Console.WriteLine("{0} Sending message {1}/{2}", DateTime.Now, index, MaxNumRequests); + producer.Send(request); + + if(2000 == index) + { + // Start the second consumer + if(destination3.IsTopic) + { + // Reset the ignored message sent count, since all previous messages + // will not have been consumed on a topic. + numIgnoredMsgsSent = 0; + } + + consumer2 = session3.CreateConsumer(destination3, "JMSType LIKE '%IGNORE'"); + consumer2.Listener += new MessageListener(OnIgnoredMessage); + } + } + + // Create a waiting loop that will coordinate the end of the test. It checks + // to see that all intended messages were received. It will continue to wait as + // long as new messages are being received. If it stops receiving messages before + // it receives everything it expects, it will eventually timeout and the test will fail. + int waitCount = 0; + int lastReceivedINongnoredMsgCount = receivedNonIgnoredMsgCount; + int lastReceivedIgnoredMsgCount = receivedIgnoredMsgCount; + + while(receivedNonIgnoredMsgCount < numNonIgnoredMsgsSent + || receivedIgnoredMsgCount < numIgnoredMsgsSent) + { + if(lastReceivedINongnoredMsgCount != receivedNonIgnoredMsgCount + || lastReceivedIgnoredMsgCount != receivedIgnoredMsgCount) + { + // Reset the wait count. + waitCount = 0; + } + else + { + waitCount++; + } + + lastReceivedINongnoredMsgCount = receivedNonIgnoredMsgCount; + lastReceivedIgnoredMsgCount = receivedIgnoredMsgCount; + + Assert.IsTrue(waitCount <= 30, String.Format("Timeout waiting for all messages to be delivered. Only {0} of {1} non-ignored messages delivered. Only {2} of {3} ignored messages delivered.", + receivedNonIgnoredMsgCount, numNonIgnoredMsgsSent, receivedIgnoredMsgCount, numIgnoredMsgsSent)); + Thread.Sleep(1000); + } + + consumer2.Dispose(); + } + } + } + } + + protected void OnNonIgnoredMessage(IMessage message) + { + receivedNonIgnoredMsgCount++; + Assert.AreEqual(message.NMSType, "ACTIVE"); +if(receivedNonIgnoredMsgCount % 200 == 0) Console.WriteLine("{0} Received non ignored message {1}", DateTime.Now, receivedNonIgnoredMsgCount); + } + + protected void OnIgnoredMessage(IMessage message) + { + receivedIgnoredMsgCount++; + Assert.AreEqual(message.NMSType, "ACTIVE.IGNORE"); + if(simulateSlowConsumer) + { + // Simulate a slow consumer It doesn't have to be too slow in a high speed environment + // in order to trigger producer flow control. + Thread.Sleep(10); + } +if(receivedIgnoredMsgCount % 200 == 0) Console.WriteLine("{0} Received ignored message {1}", DateTime.Now, receivedIgnoredMsgCount); + } + + //[Test] + public virtual void TestInvalidSelector( + //[Values(SELECTOR_TEST_QUEUE)] + string testDestRef) + { + using(IConnection connection = CreateConnection()) + { + connection.Start(); + using(ISession session = connection.CreateSession()) + { + IDestination destination = GetClearDestinationByNodeReference(session, testDestRef); + + string selector = "THIS IS NOT A VALID SELECTOR"; + + try + { + using(IMessageConsumer consumer = session.CreateConsumer(destination, selector)) + { + Assert.Fail("Consumer should have thrown an NotSupportedException"); + } + } + catch(InvalidSelectorException ex) + { + } + catch(Exception ex) + { + Assert.Fail("Wrong Exception Type Thrown: " + ex.GetType().Name); + } + } + } + } + + + } +} http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/MessageTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/MessageTest.cs b/src/test/csharp/MessageTest.cs new file mode 100644 index 0000000..6cfe45c --- /dev/null +++ b/src/test/csharp/MessageTest.cs @@ -0,0 +1,147 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using Apache.NMS.Util; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + //[TestFixture] + public class MessageTest : NMSTest + { + protected bool a = true; + protected byte b = 123; + protected char c = 'c'; + protected short d = 0x1234; + protected int e = 0x12345678; + protected long f = 0x1234567812345678; + protected string g = "Hello World!"; + protected bool h = false; + protected byte i = 0xFF; + protected short j = -0x1234; + protected int k = -0x12345678; + protected long l = -0x1234567812345678; + protected float m = 2.1F; + protected double n = 2.3; + protected byte[] o = {1, 2, 3, 4, 5}; + + protected MessageTest(NMSTestSupport testSupport) + : base(testSupport) + { + } + + //[Test] + public virtual void TestSendReceiveMessageProperties( + //[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] + MsgDeliveryMode deliveryMode, string testDestRef) + { + using(IConnection connection = CreateConnection(GetTestClientId())) + { + connection.Start(); + using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) + { + IDestination destination = GetClearDestinationByNodeReference(session, testDestRef); + using(IMessageConsumer consumer = session.CreateConsumer(destination)) + using(IMessageProducer producer = session.CreateProducer(destination)) + { + producer.DeliveryMode = deliveryMode; + IMessage request = session.CreateMessage(); + request.Properties["a"] = a; + request.Properties["b"] = b; + request.Properties["c"] = c; + request.Properties["d"] = d; + request.Properties["e"] = e; + request.Properties["f"] = f; + request.Properties["g"] = g; + request.Properties["h"] = h; + request.Properties["i"] = i; + request.Properties["j"] = j; + request.Properties["k"] = k; + request.Properties["l"] = l; + request.Properties["m"] = m; + request.Properties["n"] = n; + + try + { + request.Properties["o"] = o; + Assert.Fail("Should not be able to add a Byte[] to the Properties of a Message."); + } + catch + { + // Expected + } + + try + { + request.Properties.SetBytes("o", o); + Assert.Fail("Should not be able to add a Byte[] to the Properties of a Message."); + } + catch + { + // Expected + } + + producer.Send(request); + + IMessage message = consumer.Receive(receiveTimeout); + Assert.IsNotNull(message, "No message returned!"); + Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties."); + Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); + Assert.AreEqual(ToHex(f), ToHex(message.Properties.GetLong("f")), "map entry: f as hex"); + + // use generic API to access entries + // Perform a string only comparison here since some NMS providers are type limited and + // may return only a string instance from the generic [] accessor. Each provider should + // further test this functionality to determine that the correct type is returned if + // it is capable of doing so. + Assert.AreEqual(a.ToString(), message.Properties["a"].ToString(), "generic map entry: a"); + Assert.AreEqual(b.ToString(), message.Properties["b"].ToString(), "generic map entry: b"); + Assert.AreEqual(c.ToString(), message.Properties["c"].ToString(), "generic map entry: c"); + Assert.AreEqual(d.ToString(), message.Properties["d"].ToString(), "generic map entry: d"); + Assert.AreEqual(e.ToString(), message.Properties["e"].ToString(), "generic map entry: e"); + Assert.AreEqual(f.ToString(), message.Properties["f"].ToString(), "generic map entry: f"); + Assert.AreEqual(g.ToString(), message.Properties["g"].ToString(), "generic map entry: g"); + Assert.AreEqual(h.ToString(), message.Properties["h"].ToString(), "generic map entry: h"); + Assert.AreEqual(i.ToString(), message.Properties["i"].ToString(), "generic map entry: i"); + Assert.AreEqual(j.ToString(), message.Properties["j"].ToString(), "generic map entry: j"); + Assert.AreEqual(k.ToString(), message.Properties["k"].ToString(), "generic map entry: k"); + Assert.AreEqual(l.ToString(), message.Properties["l"].ToString(), "generic map entry: l"); + Assert.AreEqual(m.ToString(), message.Properties["m"].ToString(), "generic map entry: m"); + Assert.AreEqual(n.ToString(), message.Properties["n"].ToString(), "generic map entry: n"); + + // use type safe APIs + Assert.AreEqual(a, message.Properties.GetBool("a"), "map entry: a"); + Assert.AreEqual(b, message.Properties.GetByte("b"), "map entry: b"); + Assert.AreEqual(c, message.Properties.GetChar("c"), "map entry: c"); + Assert.AreEqual(d, message.Properties.GetShort("d"), "map entry: d"); + Assert.AreEqual(e, message.Properties.GetInt("e"), "map entry: e"); + Assert.AreEqual(f, message.Properties.GetLong("f"), "map entry: f"); + Assert.AreEqual(g, message.Properties.GetString("g"), "map entry: g"); + Assert.AreEqual(h, message.Properties.GetBool("h"), "map entry: h"); + Assert.AreEqual(i, message.Properties.GetByte("i"), "map entry: i"); + Assert.AreEqual(j, message.Properties.GetShort("j"), "map entry: j"); + Assert.AreEqual(k, message.Properties.GetInt("k"), "map entry: k"); + Assert.AreEqual(l, message.Properties.GetLong("l"), "map entry: l"); + Assert.AreEqual(m, message.Properties.GetFloat("m"), "map entry: m"); + Assert.AreEqual(n, message.Properties.GetDouble("n"), "map entry: n"); + } + } + } + } + } +} + http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/MessageTransformerTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/MessageTransformerTest.cs b/src/test/csharp/MessageTransformerTest.cs new file mode 100644 index 0000000..d954fe7 --- /dev/null +++ b/src/test/csharp/MessageTransformerTest.cs @@ -0,0 +1,124 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using Apache.NMS.Util; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + //[TestFixture] + public class MessageTransformerTest : NMSTest + { + private string propertyName = "ADDITIONAL-PROPERTY"; + private string propertyValue = "ADDITIONAL-PROPERTY-VALUE"; + + protected MessageTransformerTest(NMSTestSupport testSupport) + : base(testSupport) + { + } + + //[Test] + public virtual void TestProducerTransformer( + //[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] + MsgDeliveryMode deliveryMode) + { + using(IConnection connection = CreateConnection()) + { + connection.Start(); + using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) + { + IDestination destination = session.CreateTemporaryTopic(); + using(IMessageConsumer consumer = session.CreateConsumer(destination)) + using(IMessageProducer producer = session.CreateProducer(destination)) + { + producer.DeliveryMode = deliveryMode; + producer.ProducerTransformer = DoProducerTransform; + + IMessage message = session.CreateMessage(); + + message.Properties["Test"] = "Value"; + + producer.Send(message); + + message = consumer.Receive(TimeSpan.FromMilliseconds(5000)); + + Assert.IsNotNull(message); + Assert.IsTrue(message.Properties.Count == 2); + + Assert.AreEqual("Value", message.Properties["Test"]); + Assert.AreEqual(propertyValue, message.Properties[propertyName]); + } + } + } + } + + //[Test] + public virtual void TestConsumerTransformer( + //[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] + MsgDeliveryMode deliveryMode) + { + using(IConnection connection = CreateConnection()) + { + connection.Start(); + using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) + { + IDestination destination = session.CreateTemporaryTopic(); + using(IMessageConsumer consumer = session.CreateConsumer(destination)) + using(IMessageProducer producer = session.CreateProducer(destination)) + { + producer.DeliveryMode = deliveryMode; + + consumer.ConsumerTransformer = DoConsumerTransform; + + IMessage message = session.CreateMessage(); + + message.Properties["Test"] = "Value"; + + producer.Send(message); + + message = consumer.Receive(TimeSpan.FromMilliseconds(5000)); + + Assert.IsNotNull(message); + Assert.IsTrue(message.Properties.Count == 2, "Property Count should be 2"); + + Assert.AreEqual("Value", message.Properties["Test"], "Property 'Value' was incorrect"); + Assert.AreEqual(propertyValue, message.Properties[propertyName], "Property not inserted"); + } + } + } + } + + private IMessage DoProducerTransform(ISession session, IMessageProducer producer, IMessage message) + { + message.Properties[propertyName] = propertyValue; + + return message; + } + + private IMessage DoConsumerTransform(ISession session, IMessageConsumer consumer, IMessage message) + { + IMessage newMessage = session.CreateMessage(); + + MessageTransformation.CopyNMSMessageProperties(message, newMessage); + + newMessage.Properties[propertyName] = propertyValue; + + return newMessage; + } + } +} + http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/NMSPropertyTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/NMSPropertyTest.cs b/src/test/csharp/NMSPropertyTest.cs new file mode 100644 index 0000000..460faa8 --- /dev/null +++ b/src/test/csharp/NMSPropertyTest.cs @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using Apache.NMS.Util; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + //[TestFixture] + public class NMSPropertyTest : NMSTest + { + // standard NMS properties + protected string expectedText = "Hey this works!"; + protected string correlationID = "FooBar"; + protected MsgPriority priority = MsgPriority.Normal; + protected String type = "FooType"; + protected String groupID = "BarGroup"; + protected int groupSeq = 1; + + protected NMSPropertyTest(NMSTestSupport testSupport) + : base (testSupport) + { + } + + //[Test] + public void TestSendReceiveNMSProperties( + //[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] + MsgDeliveryMode deliveryMode, string testDestRef) + { + using(IConnection connection = CreateConnection(GetTestClientId())) + { + connection.Start(); + using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) + { + IDestination destination = GetClearDestinationByNodeReference(session, testDestRef); + using(IMessageConsumer consumer = session.CreateConsumer(destination)) + using(IMessageProducer producer = session.CreateProducer(destination)) + { + producer.Priority = priority; + producer.DeliveryMode = deliveryMode; + ITextMessage request = session.CreateTextMessage(expectedText); + + // Set the headers + request.NMSCorrelationID = correlationID; + request.NMSType = type; + request.Properties["NMSXGroupID"] = groupID; + request.Properties["NMSXGroupSeq"] = groupSeq; + + producer.Send(request); + + ITextMessage message = consumer.Receive(receiveTimeout) as ITextMessage; + + Assert.IsNotNull(message, "Did not receive an ITextMessage!"); + Assert.AreEqual(expectedText, message.Text, "Message text does not match."); + + // compare standard NMS headers + Assert.AreEqual(correlationID, message.NMSCorrelationID, "NMSCorrelationID does not match"); + Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); + Assert.AreEqual(priority, message.NMSPriority, "NMSPriority does not match"); + Assert.AreEqual(type, message.NMSType, "NMSType does not match"); + Assert.AreEqual(groupID, message.Properties["NMSXGroupID"], "NMSXGroupID does not match"); + Assert.AreEqual(groupSeq, message.Properties["NMSXGroupSeq"], "NMSXGroupSeq does not match"); + } + } + } + } + } +} http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/NMSTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/NMSTest.cs b/src/test/csharp/NMSTest.cs new file mode 100644 index 0000000..3fe3fac --- /dev/null +++ b/src/test/csharp/NMSTest.cs @@ -0,0 +1,505 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using System.Xml; +using Apache.NMS.Util; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + /// <summary> + /// Base class for test cases + /// </summary> + public abstract class NMSTest + { + protected TimeSpan receiveTimeout = TimeSpan.FromMilliseconds(15000); + + public static string ToHex(long value) + { + return String.Format("{0:x}", value); + } + + #region Constructors and test support + + private NMSTestSupport testSupport; + + static NMSTest() + { + Apache.NMS.Tracer.Trace = new NMSTracer(); + } + + protected NMSTest(NMSTestSupport testSupport) + { + this.testSupport = testSupport; + this.testSupport.TestClassType = this.GetType(); + } + + #endregion + + #region Set up and tear down + + [SetUp] + public virtual void SetUp() + { + this.testSupport.SetUp(); + } + + [TearDown] + public virtual void TearDown() + { + this.testSupport.TearDown(); + } + + #endregion + + #region Configuration file + + /// <summary> + /// The configuration document. + /// </summary> + public XmlDocument ConfigurationDocument + { + get { return this.testSupport.ConfigurationDocument; } + } + + /// <summary> + /// Loads the configuration file. + /// </summary> + /// <returns>XmlDocument of the configuration file</returns> + protected virtual XmlDocument LoadConfigFile() + { + return this.testSupport.LoadConfigFile(); + } + + /// <summary> + /// Loads the configuration file. + /// </summary> + /// <param name="configFilePath">Configuration file path</param> + /// <returns>XmlDocument of the configuration file</returns> + protected virtual XmlDocument LoadConfigFile(string configFilePath) + { + return this.testSupport.LoadConfigFile(configFilePath); + } + + /// <summary> + /// Gets the path of the configuration filename. + /// </summary> + /// <returns>Path of the configuration filename</returns> + protected virtual string GetConfigFilePath() + { + return this.testSupport.GetConfigFilePath(); + } + + /// <summary> + /// Gets the environment variable name for the configuration file path. + /// </summary> + /// <returns>Environment variable name</returns> + protected virtual string GetConfigEnvVarName() + { + return this.testSupport.GetConfigEnvVarName(); + } + + /// <summary> + /// Gets the default name for the configuration filename. + /// </summary> + /// <returns>Default name of the configuration filename</returns> + protected virtual string GetDefaultConfigFileName() + { + return this.testSupport.GetDefaultConfigFileName(); + } + + /// <summary> + /// Gets the value of the "value" attribute of the specified node. + /// </summary> + /// <param name="parentNode">Parent node</param> + /// <param name="nodeName">Node name</param> + /// <param name="defaultVaue">Default value</param> + /// <returns></returns> + protected virtual string GetNodeValueAttribute(XmlElement parentNode, + string nodeName, string defaultVaue) + { + return this.testSupport.GetNodeValueAttribute(parentNode, + nodeName, defaultVaue); + } + + #endregion + + #region URI node + + /// <summary> + /// Gets the URI node for the default configuration. + /// </summary> + /// <returns>URI node for the default configuration name</returns> + public virtual XmlElement GetURINode() + { + return this.testSupport.GetURINode(); + } + + /// <summary> + /// Gets the URI node for the default configuration. + /// </summary> + /// <param name="nameTestURI">Name of the default configuration node + /// </param> + /// <returns>URI node for the default configuration name</returns> + public virtual XmlElement GetURINode(string nameTestURI) + { + return this.testSupport.GetURINode(nameTestURI); + } + + /// <summary> + /// Gets the name of the default connection configuration to be loaded. + /// </summary> + /// <returns>Default configuration name</returns> + protected virtual string GetNameTestURI() + { + return this.testSupport.GetNameTestURI(); + } + + #endregion + + #region Factory + + private NMSConnectionFactory nmsFactory; + /// <summary> + /// The connection factory interface property. + /// </summary> + public IConnectionFactory Factory + { + get { return this.testSupport.Factory; } + } + + /// <summary> + /// Create the NMS Factory that can create NMS Connections. + /// </summary> + /// <returns>Connection factory</returns> + protected NMSConnectionFactory CreateNMSFactory() + { + return this.testSupport.CreateNMSFactory(); + } + + /// <summary> + /// Create the NMS Factory that can create NMS Connections. This + /// function loads the connection settings from the configuration file. + /// </summary> + /// <param name="nameTestURI">The named connection configuration. + /// </param> + /// <returns>Connection factory</returns> + protected NMSConnectionFactory CreateNMSFactory(string nameTestURI) + { + return this.testSupport.CreateNMSFactory(nameTestURI); + } + + /// <summary> + /// Get the parameters for the ConnectionFactory from the configuration + /// file. + /// </summary> + /// <param name="uriNode">Parent node of the factoryParams node.</param> + /// <returns>Object array of parameter objects to be passsed to provider + /// factory object. Null if no parameters are specified in + /// configuration file.</returns> + protected object[] GetFactoryParams(XmlElement uriNode) + { + return this.testSupport.GetFactoryParams(uriNode); + } + + #endregion + + #region Client id and connection + + /// <summary> + /// Client id. + /// </summary> + public string ClientId + { + get { return this.testSupport.ClientId; } + } + + /// <summary> + /// Gets a new client id. + /// </summary> + /// <returns>Client id</returns> + public virtual string GetTestClientId() + { + return this.testSupport.GetTestClientId(); + } + + /// <summary> + /// Create a new connection to the broker. + /// </summary> + /// <returns>New connection</returns> + public virtual IConnection CreateConnection() + { + return this.testSupport.CreateConnection(); + } + + /// <summary> + /// Create a new connection to the broker. + /// </summary> + /// <param name="newClientId">Client ID of the new connection.</param> + /// <returns>New connection</returns> + public virtual IConnection CreateConnection(string newClientId) + { + return this.testSupport.CreateConnection(newClientId); + } + + /// <summary> + /// Create a new connection to the broker, and start it. + /// </summary> + /// <returns>Started connection</returns> + public virtual IConnection CreateConnectionAndStart() + { + return this.testSupport.CreateConnectionAndStart(); + } + + /// <summary> + /// Create a new connection to the broker, and start it. + /// </summary> + /// <param name="newClientId">Client ID of the new connection.</param> + /// <returns>Started connection</returns> + public virtual IConnection CreateConnectionAndStart(string newClientId) + { + return this.testSupport.CreateConnectionAndStart(newClientId); + } + + #endregion + + #region Destination + + /// <summary> + /// Gets a clear destination by its configuration node reference. + /// </summary> + /// <param name="session">Session</param> + /// <param name="destinationNodeReference">Configuration node name for + /// the destination URI</param> + /// <returns>Destination</returns> + public virtual IDestination GetClearDestinationByNodeReference( + ISession session, string destinationNodeReference) + { + return this.testSupport.GetClearDestinationByNodeReference(session, destinationNodeReference); + } + + /// <summary> + /// Gets a clear destination. This will try to delete an existing + /// destination and re-create it. + /// </summary> + /// <param name="session">Session</param> + /// <param name="destinationURI">Destination URI</param> + /// <returns>Clear destination</returns> + public virtual IDestination GetClearDestination(ISession session, + string destinationURI) + { + return this.testSupport.GetClearDestination(session, destinationURI); + } + + /// <summary> + /// Gets an existing destination. Don't clear its contents. + /// </summary> + /// <param name="session">Session</param> + /// <param name="destinationNodeReference">Configuration node name for + /// the destination URI</param> + /// <returns>Destination</returns> + public virtual IDestination GetDestinationByNodeReference(ISession session, + string destinationNodeReference) + { + return this.testSupport.GetDestinationByNodeReference(session, destinationNodeReference); + } + + /// <summary> + /// Gets a destination URI. + /// </summary> + /// <param name="destinationNodeReference">Configuration node name for the + /// destination URI</param> + /// <returns>Destination URI</returns> + public virtual string GetDestinationURI(string destinationNodeReference) + { + return this.testSupport.GetDestinationURI(destinationNodeReference); + } + + #endregion + + #region Durable consumer + + /// <summary> + /// Register a durable consumer + /// </summary> + /// <param name="connectionID">Connection ID of the consumer.</param> + /// <param name="destination">Destination name to register. Supports + /// embedded prefix names.</param> + /// <param name="consumerID">Name of the durable consumer.</param> + /// <param name="selector">Selector parameters for consumer.</param> + /// <param name="noLocal"></param> + protected void RegisterDurableConsumer(string connectionID, + string destination, string consumerID, string selector, bool noLocal) + { + using(IConnection connection = CreateConnection(connectionID)) + { + connection.Start(); + using(ISession session = connection.CreateSession( + AcknowledgementMode.DupsOkAcknowledge)) + { + ITopic destinationTopic = (ITopic)SessionUtil.GetDestination(session, destination); + Assert.IsNotNull(destinationTopic, "Could not get destination topic."); + + using(IMessageConsumer consumer = session.CreateDurableConsumer(destinationTopic, consumerID, selector, noLocal)) + { + Assert.IsNotNull(consumer, "Could not create durable consumer."); + } + } + } + } + + /// <summary> + /// Unregister a durable consumer for the given connection ID. + /// </summary> + /// <param name="connectionID">Connection ID of the consumer.</param> + /// <param name="consumerID">Name of the durable consumer.</param> + protected void UnregisterDurableConsumer(string connectionID, string consumerID) + { + using(IConnection connection = CreateConnection(connectionID)) + { + connection.Start(); + using(ISession session = connection.CreateSession(AcknowledgementMode.DupsOkAcknowledge)) + { + session.DeleteDurableConsumer(consumerID); + } + } + } + + #endregion + + #region Send messages + + /// <summary> + /// Sends a specified number of text messages to the designated + /// destination. + /// </summary> + /// <param name="destination">Destination.</param> + /// <param name="deliveryMode">Delivery mode.</param> + /// <param name="count">Number of messages to be sent.</param> + public void SendMessages(IDestination destination, + MsgDeliveryMode deliveryMode, int count) + { + IConnection connection = CreateConnection(); + connection.Start(); + SendMessages(connection, destination, deliveryMode, count); + connection.Close(); + } + + /// <summary> + /// Sends a specified number of text messages to the designated + /// destination. + /// </summary> + /// <param name="connection">Connection.</param> + /// <param name="destination">Destination.</param> + /// <param name="deliveryMode">Delivery mode.</param> + /// <param name="count">Number of messages to be sent.</param> + public void SendMessages(IConnection connection, + IDestination destination, MsgDeliveryMode deliveryMode, int count) + { + ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); + SendMessages(session, destination, deliveryMode, count); + session.Close(); + } + + /// <summary> + /// Sends a specified number of text messages to the designated + /// destination. + /// </summary> + /// <param name="session">Session.</param> + /// <param name="destination">Destination.</param> + /// <param name="deliveryMode">Delivery mode.</param> + /// <param name="count">Number of messages to be sent.</param> + public void SendMessages(ISession session, IDestination destination, + MsgDeliveryMode deliveryMode, int count) + { + IMessageProducer producer = session.CreateProducer(destination); + producer.DeliveryMode = deliveryMode; + for(int i = 0; i < count; i++) + { + producer.Send(session.CreateTextMessage("" + i)); + } + producer.Close(); + } + + #endregion + + #region Check messages + + protected void AssertTextMessagesEqual(IMessage[] firstSet, IMessage[] secondSet) + { + AssertTextMessagesEqual(firstSet, secondSet, ""); + } + + protected void AssertTextMessagesEqual(IMessage[] firstSet, IMessage[] secondSet, string messsage) + { + Assert.AreEqual(firstSet.Length, secondSet.Length, "Message count does not match: " + messsage); + + for(int i = 0; i < secondSet.Length; i++) + { + ITextMessage m1 = firstSet[i] as ITextMessage; + ITextMessage m2 = secondSet[i] as ITextMessage; + + AssertTextMessageEqual(m1, m2, "Message " + (i + 1) + " did not match : "); + } + } + + protected void AssertEquals(ITextMessage m1, ITextMessage m2) + { + AssertEquals(m1, m2, ""); + } + + protected void AssertTextMessageEqual(ITextMessage m1, ITextMessage m2, string message) + { + Assert.IsFalse(m1 == null ^ m2 == null, message + ": expected {" + m1 + "}, but was {" + m2 + "}"); + + if(m1 == null) + { + return; + } + + Assert.AreEqual(m1.Text, m2.Text, message); + } + + protected void AssertEquals(IMessage m1, IMessage m2) + { + AssertEquals(m1, m2, ""); + } + + protected void AssertEquals(IMessage m1, IMessage m2, string message) + { + Assert.IsFalse(m1 == null ^ m2 == null, message + ": expected {" + m1 + "}, but was {" + m2 + "}"); + + if(m1 == null) + { + return; + } + + Assert.IsTrue(m1.GetType() == m2.GetType(), message + ": expected {" + m1 + "}, but was {" + m2 + "}"); + + if(m1 is ITextMessage) + { + AssertTextMessageEqual((ITextMessage) m1, (ITextMessage) m2, message); + } + else + { + Assert.AreEqual(m1, m2, message); + } + } + + #endregion + } +} http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/NMSTestSupport.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/NMSTestSupport.cs b/src/test/csharp/NMSTestSupport.cs new file mode 100644 index 0000000..31f2e11 --- /dev/null +++ b/src/test/csharp/NMSTestSupport.cs @@ -0,0 +1,637 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using System.Collections; +using System.IO; +using System.Reflection; +using System.Text.RegularExpressions; +using System.Xml; +using Apache.NMS.Util; +using NUnit.Framework; + +using Apache.NMS.MSMQ; + +namespace Apache.NMS.Test +{ + /// <summary> + /// Useful class for test cases support. + /// </summary> + public class NMSTestSupport + { + protected TimeSpan receiveTimeout = TimeSpan.FromMilliseconds(15000); + protected int testRun; + protected int idCounter; + + protected Type testClassType; + public Type TestClassType + { + get { return this.testClassType; } + set { this.testClassType = value; } + } + + #region Constructors + + public NMSTestSupport() + { + } + + #endregion + + #region Set up and tear down + + public virtual void SetUp() + { + this.testRun++; + } + + public virtual void TearDown() + { + } + + #endregion + + #region Configuration file + + private XmlDocument configurationDocument = null; + /// <summary> + /// The configuration document. + /// </summary> + public XmlDocument ConfigurationDocument + { + get + { + if(this.configurationDocument == null) + { + this.configurationDocument = LoadConfigFile(); + Assert.IsTrue(this.configurationDocument != null, + "Error loading configuration."); + } + + return this.configurationDocument; + } + } + + /// <summary> + /// Loads the configuration file. + /// </summary> + /// <returns>XmlDocument of the configuration file</returns> + public virtual XmlDocument LoadConfigFile() + { + return LoadConfigFile(GetConfigFilePath()); + } + + /// <summary> + /// Loads the configuration file. + /// </summary> + /// <param name="configFilePath">Configuration file path</param> + /// <returns>XmlDocument of the configuration file</returns> + public virtual XmlDocument LoadConfigFile(string configFilePath) + { + XmlDocument configDoc = new XmlDocument(); + + configDoc.Load(configFilePath); + + return configDoc; + } + + /// <summary> + /// Gets the path of the configuration filename. + /// </summary> + /// <returns>Path of the configuration filename</returns> + public virtual string GetConfigFilePath() + { + // The full path may be specified by an environment variable + string configFilePath = GetEnvVar(GetConfigEnvVarName(), ""); + bool configFound = (!string.IsNullOrEmpty(configFilePath) + && File.Exists(configFilePath)); + + // Else it may be found in well known locations + if(!configFound) + { + string[] paths = GetConfigSearchPaths(); + string configFileName = GetDefaultConfigFileName(); + + foreach(string path in paths) + { + string fullpath = Path.Combine(path, configFileName); + Tracer.Debug("\tScanning folder: " + path); + + if(File.Exists(fullpath)) + { + Tracer.Debug("\tAssembly found!"); + configFilePath = fullpath; + configFound = true; + break; + } + } + } + + Tracer.Debug("\tConfig file: " + configFilePath); + Assert.IsTrue(configFound, "Connection configuration file does not exist."); + return configFilePath; + } + + /// <summary> + /// Gets the environment variable name for the configuration file path. + /// </summary> + /// <returns>Environment variable name</returns> + public virtual string GetConfigEnvVarName() + { + return "NMSTESTCONFIGPATH"; + } + + /// <summary> + /// Gets the default name for the configuration filename. + /// </summary> + /// <returns>Default name of the configuration filename</returns> + public virtual string GetDefaultConfigFileName() + { + return "nmsprovider-test.config"; + } + + /// <summary> + /// Gets an array of paths where the configuration file sould be found. + /// </summary> + /// <returns>Array of paths</returns> + private static string[] GetConfigSearchPaths() + { + ArrayList pathList = new ArrayList(); + + // Check the current folder first. + pathList.Add(""); +#if !NETCF + AppDomain currentDomain = AppDomain.CurrentDomain; + + // Check the folder the assembly is located in. + pathList.Add(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); + if(null != currentDomain.BaseDirectory) + { + pathList.Add(currentDomain.BaseDirectory); + } + + if(null != currentDomain.RelativeSearchPath) + { + pathList.Add(currentDomain.RelativeSearchPath); + } +#endif + + return (string[]) pathList.ToArray(typeof(string)); + } + + /// <summary> + /// Gets the value of the "value" attribute of the specified node. + /// </summary> + /// <param name="parentNode">Parent node</param> + /// <param name="nodeName">Node name</param> + /// <param name="defaultVaue">Default value</param> + /// <returns></returns> + public string GetNodeValueAttribute(XmlElement parentNode, + string nodeName, string defaultVaue) + { + XmlElement node = (XmlElement)parentNode.SelectSingleNode(nodeName); + + return (node == null ? defaultVaue : node.GetAttribute("value")); + } + + #endregion + + #region URI node + + /// <summary> + /// Gets the URI node for the default configuration. + /// </summary> + /// <returns>URI node for the default configuration name</returns> + public virtual XmlElement GetURINode() + { + return GetURINode(GetNameTestURI()); + } + + /// <summary> + /// Gets the URI node for the default configuration. + /// </summary> + /// <param name="nameTestURI">Name of the default configuration node + /// </param> + /// <returns>URI node for the default configuration name</returns> + public virtual XmlElement GetURINode(string nameTestURI) + { + return (XmlElement)ConfigurationDocument.SelectSingleNode( + String.Format("/configuration/{0}", nameTestURI)); + } + + /// <summary> + /// Gets the name of the default connection configuration to be loaded. + /// </summary> + /// <returns>Default configuration name</returns> + public virtual string GetNameTestURI() + { + return "testURI"; + } + + #endregion + + #region Factory + + private NMSConnectionFactory nmsFactory; + /// <summary> + /// The connection factory interface property. + /// </summary> + public IConnectionFactory Factory + { + get + { + if(this.nmsFactory == null) + { + this.nmsFactory = CreateNMSFactory(); + + Assert.IsNotNull(this.nmsFactory, "Error creating factory."); + } + + return this.nmsFactory.ConnectionFactory; + } + } + + /// <summary> + /// Create the NMS Factory that can create NMS Connections. + /// </summary> + /// <returns>Connection factory</returns> + public NMSConnectionFactory CreateNMSFactory() + { + return CreateNMSFactory(GetNameTestURI()); + } + + /// <summary> + /// Create the NMS Factory that can create NMS Connections. This + /// function loads the connection settings from the configuration file. + /// </summary> + /// <param name="nameTestURI">The named connection configuration. + /// </param> + /// <returns>Connection factory</returns> + public NMSConnectionFactory CreateNMSFactory(string nameTestURI) + { + XmlElement uriNode = GetURINode(nameTestURI); + + Uri brokerUri = null; + object[] factoryParams = null; + if(uriNode != null) + { + // Replace any environment variables embedded inside the string. + brokerUri = new Uri(uriNode.GetAttribute("value")); + factoryParams = GetFactoryParams(uriNode); + cnxClientId = GetNodeValueAttribute(uriNode, "cnxClientId", "NMSTestClientId"); + cnxUserName = GetNodeValueAttribute(uriNode, "cnxUserName", null); + cnxPassWord = GetNodeValueAttribute(uriNode, "cnxPassWord", null); + } + + if(factoryParams == null) + { + this.nmsFactory = new Apache.NMS.NMSConnectionFactory(brokerUri); + } + else + { + this.nmsFactory = new Apache.NMS.NMSConnectionFactory(brokerUri, factoryParams); + } + + return this.nmsFactory; + } + + /// <summary> + /// Get the parameters for the ConnectionFactory from the configuration + /// file. + /// </summary> + /// <param name="uriNode">Parent node of the factoryParams node.</param> + /// <returns>Object array of parameter objects to be passsed to provider + /// factory object. Null if no parameters are specified in + /// configuration file.</returns> + public object[] GetFactoryParams(XmlElement uriNode) + { + ArrayList factoryParams = new ArrayList(); + XmlElement factoryParamsNode = (XmlElement)uriNode.SelectSingleNode("factoryParams"); + + if(factoryParamsNode != null) + { + XmlNodeList nodeList = factoryParamsNode.SelectNodes("param"); + + if(nodeList != null) + { + foreach(XmlElement paramNode in nodeList) + { + string paramType = paramNode.GetAttribute("type"); + string paramValue = paramNode.GetAttribute("value"); + + switch(paramType) + { + case "string": + factoryParams.Add(paramValue); + break; + + case "int": + factoryParams.Add(int.Parse(paramValue)); + break; + + // TODO: Add more parameter types + } + } + } + } + + if(factoryParams.Count > 0) + { + return factoryParams.ToArray(); + } + + return null; + } + + #endregion + + #region Environment variables + + /// <summary> + /// Get environment variable value. + /// </summary> + /// <param name="varName"></param> + /// <param name="defaultValue"></param> + /// <returns></returns> + public static string GetEnvVar(string varName, string defaultValue) + { +#if (PocketPC||NETCF||NETCF_2_0) + string varValue = null; +#else + string varValue = Environment.GetEnvironmentVariable(varName); +#endif + if(null == varValue) + { + varValue = defaultValue; + } + + return varValue; + } + + #endregion + + #region Client id and connection + + protected string cnxClientId; + /// <summary> + /// Client id. + /// </summary> + public string ClientId + { + get { return this.cnxClientId; } + } + + /// <summary> + /// Gets a new client id. + /// </summary> + /// <returns>Client id</returns> + public virtual string GetTestClientId() + { + System.Text.StringBuilder id = new System.Text.StringBuilder(); + + id.Append("ID:"); + id.Append(this.GetType().Name); + id.Append(":"); + id.Append(this.testRun); + id.Append(":"); + id.Append(++idCounter); + + return id.ToString(); + } + + protected string cnxUserName; + /// <summary> + /// User name. + /// </summary> + public string UserName + { + get { return this.cnxUserName; } + } + + protected string cnxPassWord; + /// <summary> + /// User pass word. + /// </summary> + public string PassWord + { + get { return this.cnxPassWord; } + } + + /// <summary> + /// Create a new connection to the broker. + /// </summary> + /// <returns>New connection</returns> + public virtual IConnection CreateConnection() + { + return CreateConnection(null); + } + + /// <summary> + /// Create a new connection to the broker. + /// </summary> + /// <param name="newClientId">Client ID of the new connection.</param> + /// <returns>New connection</returns> + public virtual IConnection CreateConnection(string newClientId) + { + IConnection newConnection; + + if(this.cnxUserName == null) + { + newConnection = Factory.CreateConnection(); + } + else + { + newConnection = Factory.CreateConnection(cnxUserName, cnxPassWord); + } + + Assert.IsNotNull(newConnection, "Connection not created"); + + if(newClientId != null) + { + newConnection.ClientId = newClientId; + } + + return newConnection; + } + + /// <summary> + /// Create a new connection to the broker, and start it. + /// </summary> + /// <returns>Started connection</returns> + public virtual IConnection CreateConnectionAndStart() + { + return CreateConnectionAndStart(null); + } + + /// <summary> + /// Create a new connection to the broker, and start it. + /// </summary> + /// <param name="newClientId">Client ID of the new connection.</param> + /// <returns>Started connection</returns> + public virtual IConnection CreateConnectionAndStart(string newClientId) + { + IConnection newConnection = CreateConnection(newClientId); + newConnection.Start(); + return newConnection; + } + + #endregion + + #region Destination + + /// <summary> + /// Gets a clear destination by its configuration node reference. + /// </summary> + /// <param name="session">Session</param> + /// <param name="destinationNodeReference">Configuration node name for + /// the destination URI</param> + /// <returns>Destination</returns> + public virtual IDestination GetClearDestinationByNodeReference( + ISession session, string destinationNodeReference) + { + string uri = GetDestinationURI(destinationNodeReference); + return GetClearDestination(session, uri); + } + + /// <summary> + /// Gets a clear destination. This will try to delete an existing + /// destination and re-create it. + /// </summary> + /// <param name="session">Session</param> + /// <param name="destinationURI">Destination URI</param> + /// <returns>Clear destination</returns> + public virtual IDestination GetClearDestination(ISession session, + string destinationURI) + { + IDestination destination; + + try + { + DeleteDestination(session, destinationURI); + destination = CreateDestination(session, destinationURI); + } + catch(Exception) + { + // Can't delete it, so lets try and purge it. + destination = SessionUtil.GetDestination(session, destinationURI); + + using(IMessageConsumer consumer = session.CreateConsumer(destination)) + { + while(consumer.Receive(TimeSpan.FromMilliseconds(750)) != null) + { + } + } + } + + return destination; + } + + /// <summary> + /// Deletes a destination. + /// </summary> + /// <param name="session">Session</param> + /// <param name="destinationURI">Destination URI</param> + protected virtual void DeleteDestination(ISession session, + string destinationURI) + { + // Only delete the destination if it can be recreated + // SessionUtil.DeleteDestination(session, destinationURI, DestinationType.Queue) + throw new NotSupportedException(); + } + + /// <summary> + /// Creates a destination. + /// </summary> + /// <param name="session">Session</param> + /// <param name="destinationURI">Destination URI</param> + protected virtual IDestination CreateDestination(ISession session, + string destinationURI) + { + throw new NotSupportedException(); + } + + /// <summary> + /// Gets an existing destination. Don't clear its contents. + /// </summary> + /// <param name="session">Session</param> + /// <param name="destinationNodeReference">Configuration node name for + /// the destination URI</param> + /// <returns>Destination</returns> + public virtual IDestination GetDestinationByNodeReference( + ISession session, string destinationNodeReference) + { + string uri = GetDestinationURI(destinationNodeReference); + + IDestination destination = SessionUtil.GetDestination(session, uri); + + return destination; + } + + /// <summary> + /// Gets a destination URI. + /// </summary> + /// <param name="destinationNodeReference">Configuration node name for + /// the destination URI</param> + /// <returns>Destination URI</returns> + public virtual string GetDestinationURI( + string destinationNodeReference) + { + string uri = null; + + if(!string.IsNullOrEmpty(destinationNodeReference)) + { + XmlElement uriNode = GetURINode(); + + if(uriNode != null) + { + uri = GetNodeValueAttribute(uriNode, destinationNodeReference, null); + } + } + + if(string.IsNullOrEmpty(uri)) + { + uri = NewDestinationURI(destinationNodeReference); + } + + return uri; + } + + /// <summary> + /// Gets a new destination URI for the specified URI scheme (valid + /// values are "queue://", "topic://", "temp-queue://" and + /// "temp-topic://"). + /// </summary> + /// <param name="destinationTypeScheme">Destination type</param> + /// <returns>Destination URI</returns> + public virtual string NewDestinationURI(string destinationTypeScheme) + { + if(destinationTypeScheme != "queue://" && + destinationTypeScheme != "topic://" && + destinationTypeScheme != "temp-queue://" && + destinationTypeScheme != "temp-topic://") + { + throw new ArgumentException( + string.Format("Invalid destination type scheme \"{0}\".", + destinationTypeScheme)); + } + + return destinationTypeScheme + "TEST." + this.TestClassType.Name + + "." + Guid.NewGuid().ToString(); + } + + #endregion + } +} http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/NMSTracer.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/NMSTracer.cs b/src/test/csharp/NMSTracer.cs new file mode 100644 index 0000000..448e232 --- /dev/null +++ b/src/test/csharp/NMSTracer.cs @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define TRACE // Force tracing to be enabled for this class + +namespace Apache.NMS.Test +{ + public class NMSTracer : Apache.NMS.ITrace + { + #region ITrace Members + public void Debug(string message) + { +#if !NETCF + System.Diagnostics.Trace.WriteLine(string.Format("DEBUG: {0}", message)); +#endif + } + + public void Error(string message) + { +#if !NETCF + System.Diagnostics.Trace.WriteLine(string.Format("ERROR: {0}", message)); +#endif + } + + public void Fatal(string message) + { +#if !NETCF + System.Diagnostics.Trace.WriteLine(string.Format("FATAL: {0}", message)); +#endif + } + + public void Info(string message) + { +#if !NETCF + System.Diagnostics.Trace.WriteLine(string.Format("INFO: {0}", message)); +#endif + } + + public void Warn(string message) + { +#if !NETCF + System.Diagnostics.Trace.WriteLine(string.Format("WARN: {0}", message)); +#endif + } + + public bool IsDebugEnabled + { + get { return true; } + } + + public bool IsErrorEnabled + { + get { return true; } + } + + public bool IsFatalEnabled + { + get { return true; } + } + + public bool IsInfoEnabled + { + get { return true; } + } + + public bool IsWarnEnabled + { + get { return true; } + } + + #endregion + } +} http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/PrimitiveMapTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/PrimitiveMapTest.cs b/src/test/csharp/PrimitiveMapTest.cs new file mode 100644 index 0000000..3e20892 --- /dev/null +++ b/src/test/csharp/PrimitiveMapTest.cs @@ -0,0 +1,170 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections; +using Apache.NMS.Util; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + [TestFixture] + public class PrimitiveMapTest + { + + bool a = true; + byte b = 123; + char c = 'c'; + short d = 0x1234; + int e = 0x12345678; + long f = 0x1234567812345678; + string g = "Hello World!"; + bool h = false; + byte i = 0xFF; + short j = -0x1234; + int k = -0x12345678; + long l = -0x1234567812345678; + IList m = CreateList(); + IDictionary n = CreateDictionary(); + + [Test] + public void TestNotMarshalled() + { + PrimitiveMap map = CreatePrimitiveMap(); + AssertPrimitiveMap(map); + } + + [Test] + public void TestMarshalled() + { + PrimitiveMap map = CreatePrimitiveMap(); + byte[] data = map.Marshal(); + map = PrimitiveMap.Unmarshal(data); + AssertPrimitiveMap(map); + } + + [Test] + public void TestMarshalledWithBigString() + { + PrimitiveMap map = CreatePrimitiveMap(); + String test = new String('a', 65538); + map.SetString("BIG_STRING", test); + byte[] data = map.Marshal(); + map = PrimitiveMap.Unmarshal(data); + AssertPrimitiveMap(map); + Assert.AreEqual(test, map.GetString("BIG_STRING")); + } + + protected PrimitiveMap CreatePrimitiveMap() + { + PrimitiveMap map = new PrimitiveMap(); + + map["a"] = a; + map["b"] = b; + map["c"] = c; + map["d"] = d; + map["e"] = e; + map["f"] = f; + map["g"] = g; + map["h"] = h; + map["i"] = i; + map["j"] = j; + map["k"] = k; + map["l"] = l; + map["m"] = m; + map["n"] = n; + + return map; + } + + protected void AssertPrimitiveMap(PrimitiveMap map) + { + // use generic API to access entries + Assert.AreEqual(a, map["a"], "generic map entry: a"); + Assert.AreEqual(b, map["b"], "generic map entry: b"); + Assert.AreEqual(c, map["c"], "generic map entry: c"); + Assert.AreEqual(d, map["d"], "generic map entry: d"); + Assert.AreEqual(e, map["e"], "generic map entry: e"); + Assert.AreEqual(f, map["f"], "generic map entry: f"); + Assert.AreEqual(g, map["g"], "generic map entry: g"); + Assert.AreEqual(h, map["h"], "generic map entry: h"); + Assert.AreEqual(i, map["i"], "generic map entry: i"); + Assert.AreEqual(j, map["j"], "generic map entry: j"); + Assert.AreEqual(k, map["k"], "generic map entry: k"); + Assert.AreEqual(l, map["l"], "generic map entry: l"); + //Assert.AreEqual(m, map["m"], "generic map entry: m"); + //Assert.AreEqual(n, map["n"], "generic map entry: n"); + + // use type safe APIs + Assert.AreEqual(a, map.GetBool("a"), "map entry: a"); + Assert.AreEqual(b, map.GetByte("b"), "map entry: b"); + Assert.AreEqual(c, map.GetChar("c"), "map entry: c"); + Assert.AreEqual(d, map.GetShort("d"), "map entry: d"); + Assert.AreEqual(e, map.GetInt("e"), "map entry: e"); + Assert.AreEqual(f, map.GetLong("f"), "map entry: f"); + Assert.AreEqual(g, map.GetString("g"), "map entry: g"); + Assert.AreEqual(h, map.GetBool("h"), "map entry: h"); + Assert.AreEqual(i, map.GetByte("i"), "map entry: i"); + Assert.AreEqual(j, map.GetShort("j"), "map entry: j"); + Assert.AreEqual(k, map.GetInt("k"), "map entry: k"); + Assert.AreEqual(l, map.GetLong("l"), "map entry: l"); + //Assert.AreEqual(m, map.GetList("m"), "map entry: m"); + //Assert.AreEqual(n, map.GetDictionary("n"), "map entry: n"); + + IList list = map.GetList("m"); + Assert.AreEqual(2, list.Count, "list size"); + Assert.IsTrue(list.Contains("Item1")); + Assert.IsTrue(list.Contains("Item2")); + + IDictionary dictionary = map.GetDictionary("n"); + Assert.AreEqual(5, dictionary.Count, "dictionary size"); + + IDictionary childMap = (IDictionary) dictionary["childMap"]; + Assert.IsNotNull(childMap); + Assert.AreEqual("childMap", childMap["name"], "childMap[name]"); + + IList childList = (IList) dictionary["childList"]; + Assert.IsNotNull(childList); + Assert.IsTrue(childList.Contains("childListElement1")); + } + + protected static IList CreateList() + { + ArrayList answer = new ArrayList(); + answer.Add("Item1"); + answer.Add("Item2"); + return answer; + } + + protected static IDictionary CreateDictionary() + { + Hashtable answer = new Hashtable(); + answer.Add("Name", "James"); + answer.Add("Location", "London"); + answer.Add("Company", "LogicBlaze"); + + Hashtable childMap = new Hashtable(); + childMap.Add("name", "childMap"); + answer.Add("childMap", childMap); + + ArrayList childList = new ArrayList(); + childList.Add("childListElement1"); + answer.Add("childList", childList); + return answer; + } + } +} http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/ProducerTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/ProducerTest.cs b/src/test/csharp/ProducerTest.cs new file mode 100644 index 0000000..ffe058e --- /dev/null +++ b/src/test/csharp/ProducerTest.cs @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + //[TestFixture] + public class ProducerTest : NMSTest + { + protected ProducerTest(NMSTestSupport testSupport) + : base(testSupport) + { + } + + //[Test] + public virtual void TestProducerSendToNullDestinationWithoutDefault() + { + using(IConnection connection = CreateConnection(GetTestClientId())) + { + connection.Start(); + using(ISession session = connection.CreateSession()) + { + IMessageProducer producer = session.CreateProducer(null); + + try + { + producer.Send(null, session.CreateTextMessage("Message")); + Assert.Fail("Producer should have thrown an NotSupportedException"); + } + catch(NotSupportedException) + { + } + catch(Exception ex) + { + Assert.Fail("Wrong Exception Type Thrown: " + ex.GetType().Name); + } + } + } + } + + //[Test] + public virtual void TestProducerSendToNullDestinationWithDefault(string testDestRef) + { + using(IConnection connection = CreateConnection(GetTestClientId())) + { + connection.Start(); + using(ISession session = connection.CreateSession()) + { + IDestination unusedDest = GetClearDestinationByNodeReference(session, testDestRef); + + IMessageProducer producer = session.CreateProducer(unusedDest); + + try + { + producer.Send(null, session.CreateTextMessage("Message")); + Assert.Fail("Producer should have thrown an InvalidDestinationException"); + } + catch(InvalidDestinationException) + { + } + catch(Exception ex) + { + Assert.Fail("Wrong Exception Type Thrown: " + ex.GetType().Name); + } + } + } + } + + //[Test] + public virtual void TestProducerSendToNonDefaultDestination(string unusedTestDestRef, string usedTestDestRef) + { + using(IConnection connection = CreateConnection(GetTestClientId())) + { + connection.Start(); + using(ISession session = connection.CreateSession()) + { + IDestination unusedDest = GetClearDestinationByNodeReference(session, unusedTestDestRef); + IDestination usedDest = GetClearDestinationByNodeReference(session, usedTestDestRef); + + IMessageProducer producer = session.CreateProducer(unusedDest); + + try + { + producer.Send(usedDest, session.CreateTextMessage("Message")); + Assert.Fail("Producer should have thrown an NotSupportedException"); + } + catch(NotSupportedException) + { + } + catch(Exception ex) + { + Assert.Fail("Wrong Exception Type Thrown: " + ex.GetType().Name); + } + } + } + } + } +} http://git-wip-us.apache.org/repos/asf/activemq-nms-msmq/blob/7274a80a/src/test/csharp/RedeliveryPolicyTest.cs ---------------------------------------------------------------------- diff --git a/src/test/csharp/RedeliveryPolicyTest.cs b/src/test/csharp/RedeliveryPolicyTest.cs new file mode 100644 index 0000000..0ee9f54 --- /dev/null +++ b/src/test/csharp/RedeliveryPolicyTest.cs @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using Apache.NMS.Policies; +using NUnit.Framework; + +namespace Apache.NMS.Test +{ + [TestFixture] + public class RedeliveryPolicyTest + { + [Test] + public void Executes_redelivery_policy_with_backoff_enabled_correctly() + { + RedeliveryPolicy policy = new RedeliveryPolicy(); + + policy.BackOffMultiplier = 2; + policy.InitialRedeliveryDelay = 5; + policy.UseExponentialBackOff = true; + + // simulate a retry of 10 times + Assert.IsTrue(policy.RedeliveryDelay(0) == 0, "redelivery delay not 5 is " + policy.RedeliveryDelay(0)); + Assert.IsTrue(policy.RedeliveryDelay(1) == 5, "redelivery delay not 10 is " + policy.RedeliveryDelay(1)); + Assert.IsTrue(policy.RedeliveryDelay(2) == 10, "redelivery delay not 20 is " + policy.RedeliveryDelay(2)); + Assert.IsTrue(policy.RedeliveryDelay(3) == 20, "redelivery delay not 40 is " + policy.RedeliveryDelay(3)); + Assert.IsTrue(policy.RedeliveryDelay(4) == 40, "redelivery delay not 80 is " + policy.RedeliveryDelay(4)); + Assert.IsTrue(policy.RedeliveryDelay(5) == 80, "redelivery delay not 160 is " + policy.RedeliveryDelay(5)); + Assert.IsTrue(policy.RedeliveryDelay(6) == 160, "redelivery delay not 320 is " + policy.RedeliveryDelay(6)); + Assert.IsTrue(policy.RedeliveryDelay(7) == 320, "redelivery delay not 640 is " + policy.RedeliveryDelay(7)); + Assert.IsTrue(policy.RedeliveryDelay(8) == 640, "redelivery delay not 1280 is " + policy.RedeliveryDelay(8)); + Assert.IsTrue(policy.RedeliveryDelay(9) == 1280, "redelivery delay not 2560 is " + policy.RedeliveryDelay(9)); + } + + [Test] + public void Executes_redelivery_policy_with_backoff_of_3_enabled_correctly() + { + RedeliveryPolicy policy = new RedeliveryPolicy(); + + policy.BackOffMultiplier = 3; + policy.InitialRedeliveryDelay = 3; + policy.UseExponentialBackOff = true; + + // simulate a retry of 10 times + Assert.IsTrue(policy.RedeliveryDelay(0) == 0, "redelivery delay not 5 is " + policy.RedeliveryDelay(0)); + Assert.IsTrue(policy.RedeliveryDelay(1) == 3, "redelivery delay not 10 is " + policy.RedeliveryDelay(1)); + Assert.IsTrue(policy.RedeliveryDelay(2) == 9, "redelivery delay not 20 is " + policy.RedeliveryDelay(2)); + Assert.IsTrue(policy.RedeliveryDelay(3) == 27, "redelivery delay not 40 is " + policy.RedeliveryDelay(3)); + Assert.IsTrue(policy.RedeliveryDelay(4) == 81, "redelivery delay not 80 is " + policy.RedeliveryDelay(4)); + Assert.IsTrue(policy.RedeliveryDelay(5) == 243, "redelivery delay not 160 is " + policy.RedeliveryDelay(5)); + Assert.IsTrue(policy.RedeliveryDelay(6) == 729, "redelivery delay not 320 is " + policy.RedeliveryDelay(6)); + Assert.IsTrue(policy.RedeliveryDelay(7) == 2187, "redelivery delay not 640 is " + policy.RedeliveryDelay(7)); + Assert.IsTrue(policy.RedeliveryDelay(8) == 6561, "redelivery delay not 1280 is " + policy.RedeliveryDelay(8)); + Assert.IsTrue(policy.RedeliveryDelay(9) == 19683, "redelivery delay not 2560 is " + policy.RedeliveryDelay(9)); + } + + [Test] + public void Executes_redelivery_policy_without_backoff_enabled_correctly() + { + RedeliveryPolicy policy = new RedeliveryPolicy(); + + policy.InitialRedeliveryDelay = 5; + + // simulate a retry of 10 times + Assert.IsTrue(policy.RedeliveryDelay(0) == 0, "redelivery delay not 0 is " + policy.RedeliveryDelay(0)); + Assert.IsTrue(policy.RedeliveryDelay(1) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(1)); + Assert.IsTrue(policy.RedeliveryDelay(2) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(2)); + Assert.IsTrue(policy.RedeliveryDelay(3) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(3)); + Assert.IsTrue(policy.RedeliveryDelay(4) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(4)); + Assert.IsTrue(policy.RedeliveryDelay(5) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(5)); + Assert.IsTrue(policy.RedeliveryDelay(6) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(6)); + Assert.IsTrue(policy.RedeliveryDelay(7) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(7)); + Assert.IsTrue(policy.RedeliveryDelay(8) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(8)); + Assert.IsTrue(policy.RedeliveryDelay(9) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(9)); + } + + [Test] + public void Should_get_collision_percent_correctly() + { + RedeliveryPolicy policy = new RedeliveryPolicy(); + + policy.CollisionAvoidancePercent = 45; + + Assert.IsTrue(policy.CollisionAvoidancePercent == 45); + } + + [Test] + public void Executes_redelivery_policy_with_collision_enabled_correctly() + { + RedeliveryPolicy policy = new RedeliveryPolicy(); + + policy.BackOffMultiplier = 2; + policy.InitialRedeliveryDelay = 5; + policy.UseExponentialBackOff = true; + policy.UseCollisionAvoidance = true; + policy.CollisionAvoidancePercent = 10; + + // simulate a retry of 10 times + int delay = policy.RedeliveryDelay(0); + Assert.IsTrue(delay == 0, "not zero is " + policy.RedeliveryDelay(0)); + delay = policy.RedeliveryDelay(1); + Assert.IsTrue(delay >= 4.5 && delay <= 5.5, "not delay >= 4.5 && delay <= 5.5 is " + policy.RedeliveryDelay(1)); + delay = policy.RedeliveryDelay(2); + Assert.IsTrue(delay >= 9 && delay <= 11, "not delay >= 9 && delay <= 11 is " + policy.RedeliveryDelay(2)); + delay = policy.RedeliveryDelay(3); + Assert.IsTrue(delay >= 18 && delay <= 22, "not delay >= 18 && delay <= 22 is " + policy.RedeliveryDelay(3)); + delay = policy.RedeliveryDelay(4); + Assert.IsTrue(delay >= 36 && delay <= 44, "not delay >= 36 && delay <= 44 is " + policy.RedeliveryDelay(4)); + delay = policy.RedeliveryDelay(5); + Assert.IsTrue(delay >= 72 && delay <= 88, "not delay >= 72 && delay <= 88 is " + policy.RedeliveryDelay(5)); + delay = policy.RedeliveryDelay(6); + Assert.IsTrue(delay >= 144 && delay <= 176, "not delay >= 144 && delay <= 176 is " + policy.RedeliveryDelay(6)); + delay = policy.RedeliveryDelay(7); + Assert.IsTrue(delay >= 288 && delay <= 352, "not delay >= 288 && delay <= 352 is " + policy.RedeliveryDelay(7)); + delay = policy.RedeliveryDelay(8); + Assert.IsTrue(delay >= 576 && delay <= 704, "not delay >= 576 && delay <= 704 is " + policy.RedeliveryDelay(8)); + delay = policy.RedeliveryDelay(9); + Assert.IsTrue(delay >= 1152 && delay <= 1408, "not delay >= 1152 && delay <= 1408 is " + policy.RedeliveryDelay(9)); + delay = policy.RedeliveryDelay(10); + Assert.IsTrue(delay >= 2304 && delay <= 2816, "not delay >= 2304 && delay <= 2816 is " + policy.RedeliveryDelay(10)); + } + } +}
