/* * 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; namespace Apache.NMS.Test { /// /// Useful class for test cases support. /// 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; /// /// The configuration document. /// public XmlDocument ConfigurationDocument { get { if(this.configurationDocument == null) { this.configurationDocument = LoadConfigFile(); Assert.IsTrue(this.configurationDocument != null, "Error loading configuration."); } return this.configurationDocument; } } /// /// Loads the configuration file. /// /// XmlDocument of the configuration file public virtual XmlDocument LoadConfigFile() { return LoadConfigFile(GetConfigFilePath()); } /// /// Loads the configuration file. /// /// Configuration file path /// XmlDocument of the configuration file public virtual XmlDocument LoadConfigFile(string configFilePath) { XmlDocument configDoc = new XmlDocument(); configDoc.Load(configFilePath); return configDoc; } /// /// Gets the path of the configuration filename. /// /// Path of the configuration filename 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; } /// /// Gets the environment variable name for the configuration file path. /// /// Environment variable name public virtual string GetConfigEnvVarName() { return "NMSTESTCONFIGPATH"; } /// /// Gets the default name for the configuration filename. /// /// Default name of the configuration filename public virtual string GetDefaultConfigFileName() { return "nmsprovider-test.config"; } /// /// Gets an array of paths where the configuration file sould be found. /// /// Array of paths 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)); } /// /// Gets the value of the "value" attribute of the specified node. /// /// Parent node /// Node name /// Default value /// 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 /// /// Gets the URI node for the default configuration. /// /// URI node for the default configuration name public virtual XmlElement GetURINode() { return GetURINode(GetNameTestURI()); } /// /// Gets the URI node for the default configuration. /// /// Name of the default configuration node /// /// URI node for the default configuration name public virtual XmlElement GetURINode(string nameTestURI) { return (XmlElement)ConfigurationDocument.SelectSingleNode( String.Format("/configuration/{0}", nameTestURI)); } /// /// Gets the name of the default connection configuration to be loaded. /// /// Default configuration name public virtual string GetNameTestURI() { return "testURI"; } #endregion #region Factory private NMSConnectionFactory nmsFactory; /// /// The connection factory interface property. /// public IConnectionFactory Factory { get { if(this.nmsFactory == null) { this.nmsFactory = CreateNMSFactory(); Assert.IsNotNull(this.nmsFactory, "Error creating factory."); } return this.nmsFactory.ConnectionFactory; } } /// /// Create the NMS Factory that can create NMS Connections. /// /// Connection factory public NMSConnectionFactory CreateNMSFactory() { return CreateNMSFactory(GetNameTestURI()); } /// /// Create the NMS Factory that can create NMS Connections. This /// function loads the connection settings from the configuration file. /// /// The named connection configuration. /// /// Connection factory 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); clientId = GetNodeValueAttribute(uriNode, "clientId", "NMSTestClientId"); userName = GetNodeValueAttribute(uriNode, "userName", null); passWord = GetNodeValueAttribute(uriNode, "passWord", null); } if(factoryParams == null) { this.nmsFactory = new Apache.NMS.NMSConnectionFactory(brokerUri); } else { this.nmsFactory = new Apache.NMS.NMSConnectionFactory(brokerUri, factoryParams); } return this.nmsFactory; } /// /// Get the parameters for the ConnectionFactory from the configuration /// file. /// /// Parent node of the factoryParams node. /// Object array of parameter objects to be passsed to provider /// factory object. Null if no parameters are specified in /// configuration file. 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 /// /// Get environment variable value. /// /// /// /// 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 clientId; /// /// Client id. /// public string ClientId { get { return this.clientId; } } /// /// Gets a new client id. /// /// Client id 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 userName; /// /// User name. /// public string UserName { get { return this.userName; } } protected string passWord; /// /// User pass word. /// public string PassWord { get { return this.passWord; } } /// /// Create a new connection to the broker. /// /// New connection public virtual IConnection CreateConnection() { return CreateConnection(null); } /// /// Create a new connection to the broker. /// /// Client ID of the new connection. /// New connection public virtual IConnection CreateConnection(string newClientId) { IConnection newConnection; if(this.userName == null) { newConnection = Factory.CreateConnection(); } else { newConnection = Factory.CreateConnection(userName, passWord); } Assert.IsNotNull(newConnection, "Connection not created"); if(newClientId != null) { newConnection.ClientId = newClientId; } return newConnection; } /// /// Create a new connection to the broker, and start it. /// /// Started connection public virtual IConnection CreateConnectionAndStart() { return CreateConnectionAndStart(null); } /// /// Create a new connection to the broker, and start it. /// /// Client ID of the new connection. /// Started connection public virtual IConnection CreateConnectionAndStart(string newClientId) { IConnection newConnection = CreateConnection(newClientId); newConnection.Start(); return newConnection; } #endregion #region Destination /// /// Gets a clear destination. /// /// Session /// Destination type /// Configuration node name for the /// destination URI /// Destination public virtual IDestination GetClearDestination(ISession session, DestinationType type, string destinationRef) { string uri = GetDestinationURI(type, destinationRef); return GetClearDestination(session, uri); } /// /// Gets a clear destination. This will try to delete an existing /// destination and re-create it. /// /// Session /// Destination URI /// Clear destination 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; } /// /// Deletes a destination. /// /// Session /// Destination URI 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(); } /// /// Creates a destination. /// /// Session /// Destination URI protected virtual IDestination CreateDestination(ISession session, string destinationURI) { throw new NotSupportedException(); } /// /// Gets an existing destination. Don't clear its contents. /// /// Session /// Destination type /// Configuration node name for the /// destination URI /// Destination public virtual IDestination GetDestination(ISession session, DestinationType type, string destinationRef) { string uri = GetDestinationURI(type, destinationRef); IDestination destination = SessionUtil.GetDestination(session, uri); return destination; } /// /// Gets a destination URI. /// /// Destination type /// Configuration node name for the /// destination URI /// Destination URI public virtual string GetDestinationURI( DestinationType type, string destinationRef) { string uri = null; if(!string.IsNullOrEmpty(destinationRef)) { XmlElement uriNode = GetURINode(); if(uriNode != null) { uri = GetNodeValueAttribute(uriNode, destinationRef, null); } } if(string.IsNullOrEmpty(uri)) { uri = NewDestinationURI(type); } return uri; } /// /// Gets a new destination URI. /// /// Destination type /// Destination URI public virtual string NewDestinationURI(DestinationType type) { string name = "TEST." + this.TestClassType.Name + "." + Guid.NewGuid().ToString(); string scheme; switch(type) { case DestinationType.Queue: scheme = "queue://"; break; case DestinationType.Topic: scheme = "topic://"; break; case DestinationType.TemporaryQueue: scheme = "temp-queue://"; break; case DestinationType.TemporaryTopic: scheme = "temp-topic://"; break; default: throw new ArgumentException("type: " + type); } return scheme + name; } #endregion } }