public ConcurrentTestStepWrapper(TestStepBase testStep, Context ctx ) { TestStep = testStep; _logger = new Logger(); _logger.ConcurrentExecutionMode = true; _context = ctx.CloneForConcurrentUse(_logger); }
public void Execute(XmlNode testConfig, Context context) { var configuration = new BizUnitXmlCompareConfiguration(testConfig, context); string foundFilePath = GetFoundFilePath(context, configuration); try { StringBuilder diff; bool comparisonResult = Compare(out diff, configuration.GoalFilePath, foundFilePath, configuration.StringsToSearchAndReplace, configuration.ElementsToExclude, configuration.AttributesToExclude, configuration.IgnoreChildOrder, configuration.IgnoreComments); if (!comparisonResult) { context.LogInfo(string.Format(CultureInfo.CurrentCulture, "This is the diff result: {0}", diff)); throw new ApplicationException(string.Format(CultureInfo.CurrentCulture, "Xml comparison failed between {0} and {1}. This is the diff result: {2}", foundFilePath, configuration.GoalFilePath, diff)); } context.LogInfo("Files are identical."); } finally { if (!string.IsNullOrEmpty(foundFilePath) && configuration.DeleteFile) { File.Delete(foundFilePath); context.LogInfo(string.Format(CultureInfo.CurrentCulture, "Found file ({0}) deleted.", foundFilePath)); } } }
/// <summary> /// TestStepBase.Execute() implementation /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Execute(Context context) { context.LogInfo("About to create the directory: {0}", DirectoryName); System.IO.Directory.CreateDirectory(DirectoryName); }
public TestExecuter(string configFile) { Logger logger = new Logger(); this.context = new Context(this, logger); XmlDocument testConfig = new XmlDocument(); testConfig.Load(configFile); // Get test name... XmlNode nameNode = testConfig.SelectSingleNode("/TestCase/@testName"); if ( null != nameNode ) { this.testName = nameNode.Value; } logger.WriteLine(" "); logger.WriteLine(new string('-', 79)); logger.WriteLine(" S T A R T" ); logger.WriteLine( " " ); string userName = GetUserName(); logger.WriteLine(string.Format("Test: {0} started @ {1} by {2}", this.testName, GetNow(), userName)); logger.WriteLine(new string('-', 79)); // Get test setup / execution / teardown steps this.setupSteps = testConfig.SelectNodes("/TestCase/TestSetup/*"); this.executeSteps = testConfig.SelectNodes("/TestCase/TestExecution/*"); this.teardownSteps = testConfig.SelectNodes("/TestCase/TestCleanup/*"); this.logger = logger; }
/// <summary> /// TestStepBase.Execute() implementation /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Execute(Context context) { context.LogInfo("About to wait for {0} milli seconds...", _timeOut.ToString()); Thread.Sleep(_timeOut); context.LogInfo("A delay of {0} milli second has successfully completed.", _timeOut.ToString()); }
public ConcurrentTestStepWrapper(BizUnitTestStepWrapper stepWrapper, Context ctx ) { StepWrapper = stepWrapper; // TODO:.... ILogger _logger = new Logger(); _logger.ConcurrentExecutionMode = true; _context = ctx.CloneForConcurrentUse(_logger); }
/// <summary> /// Helper method to execute an HTTP request-response /// </summary> /// /// <param name="url">The HTTP Url</param> /// <param name="payload">Byte array conatining the request data</param> /// <param name="requestTimeout">The request timeout value</param> /// <param name="context">The BizUnit context object which holds state and is passed between test steps</param> /// <returns>response MemoryStream</returns> public static MemoryStream SendRequestData(String url, byte[] payload, int requestTimeout, Context context) { WebResponse result = null; MemoryStream response = new MemoryStream(); Stream responseStream = null; Stream requestStream = null; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.Timeout = requestTimeout; req.ContentType = "text/xml; charset=\"utf-8\""; req.ContentLength = payload.Length; requestStream = req.GetRequestStream(); requestStream.Write( payload, 0, payload.Length ); result = req.GetResponse(); responseStream = result.GetResponseStream(); const int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int count = responseStream.Read( buffer, 0, bufferSize ); while (count > 0) { response.Write(buffer, 0, count); count = responseStream.Read(buffer, 0, bufferSize ); } response.Seek(0, SeekOrigin.Begin); } catch(Exception e) { context.LogException( e ); throw; } finally { if ( null != result ) { result.Close(); } if ( null != responseStream ) { responseStream.Close(); } if ( null != requestStream ) { requestStream.Close(); } } return response; }
/// <summary> /// Execute() /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Execute(Context context) { context.LogInfo("Using database connection string: {0}", ConnectionString); string sqlQueryToExecute = SQLQuery.GetFormattedSqlQuery(context); // Sleep for delay seconds... if (0 < DelayBeforeCheck) { context.LogInfo("Sleeping for: {0} seconds", DelayBeforeCheck); System.Threading.Thread.Sleep(DelayBeforeCheck*1000); } context.LogInfo("Executing database query: {0}", sqlQueryToExecute); DataSet ds = FillDataSet(ConnectionString, sqlQueryToExecute); if (NumberOfRowsExpected != ds.Tables[0].Rows.Count) { throw new ApplicationException(string.Format("Number of rows expected to be returned by the query does not match the value specified in the teststep. Number of rows the NnumberOfRowsExpected were: {0}, actual: {1}", NumberOfRowsExpected, ds.Tables[0].Rows.Count)); } context.LogInfo("NumberOfRowsExpected: {0}, actual number returned: {1}", NumberOfRowsExpected, ds.Tables[0].Rows.Count); if (0 == NumberOfRowsExpected) { return; } if (0 < DbRowsToValidate.Count) { int rowCount = 0; foreach (var dbRowToValidate in DbRowsToValidate) { context.LogInfo("Validating row number: {0}", rowCount); var resultRow = ds.Tables[0].Rows[rowCount]; ; var cells = dbRowToValidate.Cells; foreach (DbCellToValidate cell in cells) { object dbData = resultRow[cell.ColumnName]; var dbDataStringValue = string.Empty; if (0 == ValidateData(dbData, cell.ExpectedValue, ref dbDataStringValue)) { context.LogInfo("Validation succeeded for field: {0}. Expected value: {1}", cell.ColumnName, dbDataStringValue); } else { throw new Exception(String.Format("Validation failed for field: {0}. Expected value: {1}, actual value: {2}", cell.ColumnName, cell.ExpectedValue, dbDataStringValue)); } } rowCount++; } } }
internal override void Load(XmlNode testConfig, Context context) { GoalFilePath = context.ReadConfigAsString(testConfig, "GoalFile"); SearchDirectory = context.ReadConfigAsString(testConfig, "SearchDirectory"); Filter = context.ReadConfigAsString(testConfig, "Filter"); Timeout = context.ReadConfigAsUInt32(testConfig, "Timeout"); DeleteFile = context.ReadConfigAsBool(testConfig, "DeleteFile", true); Exclusions = ParseExclusions(testConfig); }
public void GetFoundFileDirectoryNotFoundException() { var context = new Context(); var configuration = new BizUnitFlatfileCompareConfiguration(); configuration.SearchDirectory = @"c:\thisFolderShouldnotExist"; configuration.Filter = "*.should.not.be.found"; configuration.Timeout = 1000; Assert.Throws<DirectoryNotFoundException>(delegate { BizUnitCompare.BizUnitCompare.GetFoundFilePath(context, configuration); }); }
private static void VerifyParameters(Context context, BizUnitCompareConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException("configuration", "Parameter configuration can not be null"); } if (context == null) { throw new ArgumentNullException("context", "Parameter context can not be null"); } }
internal void Test() { var config = new XmlDocument(); var context = new Context(); config.Load(@"XmlCompare\testConfig.xml"); XmlNode configPart = config.SelectSingleNode("/TestStep"); context.Add("searchDirectory", Directory.GetCurrentDirectory() + @"\XmlCompare"); var comparer = new BizUnitCompare.XmlCompare.XmlCompare(); comparer.Execute(configPart, context); }
internal override void Load(XmlNode testConfig, Context context) { GoalFilePath = context.ReadConfigAsString(testConfig, "GoalFile"); SearchDirectory = context.ReadConfigAsString(testConfig, "SearchDirectory"); Filter = context.ReadConfigAsString(testConfig, "Filter"); Timeout = context.ReadConfigAsUInt32(testConfig, "Timeout"); DeleteFile = context.ReadConfigAsBool(testConfig, "DeleteFile", true); IgnoreChildOrder = context.ReadConfigAsBool(testConfig, "IgnoreChildOrder", true); IgnoreComments = context.ReadConfigAsBool(testConfig, "IgnoreComments", true); ElementsToExclude = ParseElementExclusions(testConfig); AttributesToExclude = ParseAttributeExclusions(testConfig); StringsToSearchAndReplace = ParseReplacements(testConfig); }
/// <summary> /// Helper method to read a message from an MQ Series queue /// </summary> /// /// <param name="queueManagerName">The name of the MQ Series queue manager</param> /// <param name="queueName">The name of the MQ Series queue to read from</param> /// <param name="waitDelay">The time to wait for the message to be read from the queue</param> /// <param name="context">The BizUnit context object which holds state and is passed between test steps</param> /// <param name="msgID">[out] the MQ Series message ID</param> /// <returns>String containing the data from the MQ series message</returns> static public string ReadMessage(string queueManagerName, string queueName, int waitDelay, Context context, out byte[] msgID) { MQQueueManager queueManager = null; MQQueue receiveQueue = null; string message = null; try { context.LogInfo("Opening queue manager: \"{0}\"", queueManagerName); queueManager = new MQQueueManager(queueManagerName); context.LogInfo("Opening queue: \"{0}\"", queueName); receiveQueue = queueManager.AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); MQMessage mqMsg = new MQMessage(); MQGetMessageOptions mqMsgOpts = new MQGetMessageOptions(); mqMsgOpts.WaitInterval = waitDelay*1000; mqMsgOpts.Options = MQC.MQGMO_WAIT; context.LogInfo("Reading message from queue '{0}'.", queueName); receiveQueue.Get(mqMsg,mqMsgOpts); if(mqMsg.Format.CompareTo(MQC.MQFMT_STRING)==0) { mqMsg.Seek(0); message = System.Text.UTF8Encoding.UTF8.GetString(mqMsg.ReadBytes(mqMsg.MessageLength)); msgID = mqMsg.MessageId; } else { throw new NotSupportedException(string.Format("Unsupported message format: '{0}' read from queue: {1}.", mqMsg.Format, queueName)); } } finally { if (receiveQueue != null) { receiveQueue.Close(); } if (queueManager != null) { queueManager.Close(); } } return message; }
/// <summary> /// ITestStep.Execute() implementation /// </summary> /// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public void Execute(System.Xml.XmlNode testConfig , Context context) { // Using Policy Tester // Retrieve Rule-Set from Policy file string RuleStoreName = context.ReadConfigAsString(testConfig, "RuleStoreName"); string RuleSetInfoCollectionName =context.ReadConfigAsString(testConfig, "RuleSetInfoCollectionName"); string DebugTracking = context.ReadConfigAsString(testConfig, "DebugTracking"); string SampleXML = context.ReadConfigAsString(testConfig, "SampleXML"); string XSD = context.ReadConfigAsString(testConfig, "XSD"); string ResultFile = context.ReadConfigAsString(testConfig, "ResultFile"); RuleStore ruleStore = new FileRuleStore(RuleStoreName); RuleSetInfoCollection rsInfo = ruleStore.GetRuleSets(RuleSetInfoCollectionName, RuleStore.Filter.Latest); if (rsInfo.Count != 1) { // oops ... error throw new ApplicationException(); } RuleSet ruleset = ruleStore.GetRuleSet(rsInfo[0]); // Create an instance of the DebugTrackingInterceptor DebugTrackingInterceptor dti = new DebugTrackingInterceptor(DebugTracking); // Create an instance of the Policy Tester class PolicyTester policyTester = new PolicyTester(ruleset); XmlDocument xd1 = new XmlDocument(); xd1.Load(SampleXML); TypedXmlDocument doc1 = new TypedXmlDocument(XSD, xd1); // Execute Policy Tester try { policyTester.Execute(doc1, dti); } catch (Exception e) { context.LogException(e); throw; } FileInfo f = new FileInfo(ResultFile); StreamWriter w = f.CreateText(); w.Write(doc1.Document.OuterXml); w.Close(); }
public void GetFoundFileLockedFile() { var context = new Context(); var configuration = new BizUnitFlatfileCompareConfiguration(); configuration.SearchDirectory = Directory.GetCurrentDirectory(); configuration.Filter = "*.test"; configuration.Timeout = 1000; string fileToCreatePath = Directory.GetCurrentDirectory() + @"\test.test"; FileStream fileStream = PrepareFileSystem(configuration, fileToCreatePath); Assert.Throws<FileNotFoundException>(delegate { BizUnitCompare.BizUnitCompare.GetFoundFilePath(context, configuration); }); fileStream.Dispose(); }
internal static string GetFoundFilePath(Context context, BizUnitCompareConfiguration configuration) { VerifyParameters(context, configuration); context.LogInfo(string.Format(CultureInfo.CurrentCulture, "Waiting for file (in: {0}) for {1} seconds.", configuration.SearchDirectory, configuration.Timeout/1000)); DateTime endTime = DateTime.Now.AddMilliseconds(configuration.Timeout).AddMilliseconds(1); bool fileFound = false; string foundFilePath = string.Empty; do { string[] files = Directory.GetFiles(configuration.SearchDirectory, configuration.Filter, SearchOption.TopDirectoryOnly); if (files.Length > 0) { try { string fileData; using (FileStream testFileStream = File.Open(files[0], FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var testFileStreamReader = new StreamReader(testFileStream)) { fileData = testFileStreamReader.ReadToEnd(); } // it might be tempting to try to load the found file into an XmlDocument here, // but the user might have configured replacements which will turn an invalid document into a valid XML. } context.LogInfo(string.Format(CultureInfo.CurrentCulture, "File found: {0}", files[0])); context.LogInfo(fileData); foundFilePath = files[0]; fileFound = true; } catch (IOException) { context.LogWarning("Error while opening found file ({0}) for reading. Will retry continously until timeout expires.", files[0]); } } Thread.Sleep(100); } while (DateTime.Now < endTime && !fileFound); if (!fileFound) { throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, "No files found in {0} within the given timeout ({1})", configuration.SearchDirectory, configuration.Timeout)); } return foundFilePath; }
public void XmlContextLoader_Positive() { ContextLoaderStepBuilder clsb = new ContextLoaderStepBuilder("BizUnit.XmlContextLoader", null); object[] args = new object[2]; args[0] = "MyContextKey"; args[1] = "*[local-name()='PurchaseOrder' and namespace-uri()='http://SendMail.PurchaseOrder']/*[local-name()='PONumber' and namespace-uri()='']"; clsb.SetProperty("XPathExpressions", args); Context ctx = new Context(); Stream data = ResourceLoaderHelper.GetResourceDataAsStream("Data", "PurchaseOrder001.xml"); clsb.ContextLoaderStep.Validate(ctx); clsb.ContextLoaderStep.ExecuteContextLoader(data, ctx); Assert.AreEqual("PONumber_0", ctx.GetValue("MyContextKey")); }
public void TestDisposeWithNoDisposables() { Context context = new Context(); context.DisposeMembersOnTestCaseCompletion = true; IEnumerable notDisposable = mockery.DynamicMock<IEnumerable>(); using (mockery.Record()) { context.Add("NotDisposableClassKey", notDisposable); } using (mockery.Playback()) { BizUnit.BizUnit bizUnit = new BizUnit.BizUnit(new BizUnitTestCase("TestDisposeWithNoDisposables"), context); bizUnit.RunTest(); } }
public void GetFoundFileFindFile() { var context = new Context(); var configuration = new BizUnitFlatfileCompareConfiguration(); configuration.SearchDirectory = Directory.GetCurrentDirectory(); configuration.Filter = "*.test"; configuration.Timeout = 1000; string fileToCreatePath = Directory.GetCurrentDirectory() + @"\test.test"; FileStream fileStream = PrepareFileSystem(configuration, fileToCreatePath); fileStream.Dispose(); string foundFile = BizUnitCompare.BizUnitCompare.GetFoundFilePath(context, configuration); Assert.AreEqual(fileToCreatePath, foundFile); }
///<summary> /// Validates the SqlQuery ///</summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> ///<exception cref="ArgumentNullException"></exception> public void Validate(Context context) { string sqlQuery = GetFormattedSqlQuery(context); if (string.IsNullOrEmpty(sqlQuery)) { throw new ArgumentNullException("The Sql Query cannot be formmatted correctly"); } for (int c = 0; c < QueryParameters.Count; c++) { if (QueryParameters[c] is string) { QueryParameters[c] = context.SubstituteWildCards((string)QueryParameters[c]); } } RawSqlQuery = context.SubstituteWildCards(RawSqlQuery); }
public void Execute(XmlNode testConfig, Context context) { var configuration = new BizUnitFlatfileCompareConfiguration(testConfig, context); string foundFilePath = BizUnitCompare.GetFoundFilePath(context, configuration); using (MemoryStream cleanedFoundData = FlatfileCleaner.RemoveExclusions(foundFilePath, configuration.Exclusions)) { using (MemoryStream cleanedGoalData = FlatfileCleaner.RemoveExclusions(configuration.GoalFilePath, configuration.Exclusions)) { // just to be sure. cleanedFoundData.Seek(0, SeekOrigin.Begin); cleanedGoalData.Seek(0, SeekOrigin.Begin); if (cleanedFoundData.Length != cleanedGoalData.Length) { throw new ApplicationException(string.Format(CultureInfo.CurrentCulture, "Flatfile comparison failed (different length) between {0} and {1}.", foundFilePath, configuration.GoalFilePath)); } try { do { int foundByte = cleanedFoundData.ReadByte(); int goalByte = cleanedGoalData.ReadByte(); if (foundByte != goalByte) { throw new ApplicationException(string.Format(CultureInfo.CurrentCulture, "Flatfile comparison failed at offset {2} between {0} and {1}.", foundFilePath, configuration.GoalFilePath, cleanedFoundData.Position - 1)); } } while (!(cleanedFoundData.Position >= cleanedFoundData.Length)); context.LogInfo("Files are identical."); } finally { if (!string.IsNullOrEmpty(foundFilePath) && configuration.DeleteFile) { File.Delete(foundFilePath); context.LogInfo(string.Format(CultureInfo.CurrentCulture, "Found file ({0}) deleted.", foundFilePath)); } } } } }
public override void Execute(Context context) { _request = RequestBody.Load(context); context.LogXmlData("Request", _request, true); _response = CallWebMethod( _request, ServiceUrl, Action, Username, Password, context); Stream responseForPostProcessing = _response; foreach(var subStep in SubSteps) { responseForPostProcessing = subStep.Execute(responseForPostProcessing, context); } }
public override Stream Load(Context context) { var doc = new XmlDocument(); context.LogInfo("Loading file: {0}", FilePath); doc.Load(FilePath); if (null != UpdateXml) { foreach (var xpath in UpdateXml) { context.LogInfo("Selecting node in document, description: {0}, XPath: {1}", xpath.Description, xpath.XPath); XPathNavigator xpn = doc.CreateNavigator(); XPathNavigator node = xpn.SelectSingleNode(xpath.XPath); if (null == node) { context.LogError("XPath expression failed to find node"); throw new ApplicationException(String.Format("Node not found: {0}", xpath.Description)); } if (!string.IsNullOrEmpty(xpath.ContextKey)) { context.LogInfo("Updating XmlNode with value from context key: {0}", xpath.ContextKey); node.SetValue(context.GetValue(xpath.ContextKey)); } else { context.LogInfo("Updating XmlNode with value: {0}", xpath.Value); node.SetValue(xpath.Value); } } } MemoryStream ms = new MemoryStream(); doc.Save(ms); ms.Seek(0, SeekOrigin.Begin); return ms; }
public void TestDisposeWithException() { Context context = new Context(); context.DisposeMembersOnTestCaseCompletion = true; IDisposable disposable = mockery.DynamicMock<IDisposable>(); IEnumerable notDisposable = mockery.DynamicMock<IEnumerable>(); context.Add("DisposableClassKey", disposable); context.Add("NotDisposableClassKey", notDisposable); using (mockery.Record()) { disposable.Dispose(); LastCall.Throw(new ApplicationException("Exception thrown during dispose.")).Repeat.Once(); } using (mockery.Playback()) { BizUnit.BizUnit bizUnit = new BizUnit.BizUnit(new BizUnitTestCase("TestDisposeWithException"), context); bizUnit.RunTest(); } }
///<summary> /// Formats the query string, replacing the formatting instructions in cref="RawSqlQuery" with the parameters in cref="QueryParameters" ///</summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> ///<returns></returns> public string GetFormattedSqlQuery(Context context) { object[] objParams = null; if (QueryParameters.Count > 0) { objParams = new object[QueryParameters.Count]; int c = 0; foreach (var obj in QueryParameters) { object objValue; if (obj.GetType() == typeof(ContextProperty)) { objValue = ((ContextProperty)obj).GetPropertyValue(context); } else { objValue = obj; } if (objValue.GetType() == typeof(System.DateTime)) { // Convert to SQL Datetime objParams[c++] = ((DateTime)objValue).ToString("yyyy-MM-dd HH:mm:ss.fff"); } else { objParams[c++] = objValue; } } return string.Format(RawSqlQuery, objParams); } return RawSqlQuery; }
/// <summary> /// Execute() implementation /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Execute(Context context) { FileStream dstFs = null; Stream srcFs = null; try { context.LogInfo("FileCreateStep about to copy the data from File: {0} to the File: {1}", _sourcePath, _creationPath); srcFs = DataSource.Load(context); dstFs = File.Create(_creationPath); var buff = new byte[BuffSize]; int read = srcFs.Read(buff, 0, BuffSize); while (read > 0) { dstFs.Write(buff, 0, read); read = srcFs.Read(buff, 0, BuffSize); } context.Add(FileCreationPathContextKey, _creationPath, true); } finally { if (null != srcFs) { srcFs.Close(); } if (null != dstFs) { dstFs.Close(); } } }
public abstract void Validate(Context context);
public abstract void Execute(Context context);
public override Stream Load(Context context) { return StreamHelper.LoadFileToStream(FilePath); }