Skip to content

Commit

Permalink
Added NUnit DataDrive from Excel (xlsx) files, reviewer pstryczek
Browse files Browse the repository at this point in the history
  • Loading branch information
raczeja committed Feb 12, 2018
1 parent e2b01c4 commit ae935e2
Show file tree
Hide file tree
Showing 9 changed files with 253 additions and 37 deletions.
1 change: 1 addition & 0 deletions Objectivity.Test.Automation.Tests.NUnit/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
<add key="PathToFirefoxProfile" value="C:\Users\ci_objectivity\AppData\Roaming\Mozilla\Firefox\Profiles"/>
<!--DataDrivenFile-->
<add key="DataDrivenFile" value="\DataDriven\DataDriven.xml"/>
<add key="DataDrivenFileXlsx" value="\DataDriven\DataDriven.xlsx"/>
</appSettings>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<targets>
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,24 @@ namespace Objectivity.Test.Automation.Tests.NUnit.DataDriven
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Common.Exceptions;
using global::NUnit.Framework;
using NLog;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

/// <summary>
/// XML DataDriven methods for NUnit test framework <see href="https://github.com/ObjectivityLtd/Test.Automation/wiki/DataDriven-tests-from-Xml-files">More details on wiki</see>
/// </summary>
public static class DataDrivenHelper
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

/// <summary>
/// Reads the data drive file and set test name.
/// </summary>
Expand Down Expand Up @@ -117,6 +123,100 @@ public static IEnumerable<TestCaseData> ReadDataDriveFile(string folder, string
return doc.Descendants(testData).Select(element => element.Attributes().ToDictionary(k => k.Name.ToString(), v => v.Value)).Select(testParams => new TestCaseData(testParams));
}

/// <summary>
/// Reads the Excel data drive file and optionaly set test name.
/// </summary>
/// <param name="path">Full path to Excel DataDriveFile file</param>
/// <param name="sheetName">Name of the sheet at xlsx file.</param>
/// <param name="diffParam">Optional values of listed parameters will be used in test case name.</param>
/// <param name="testName">Optional name of the test, use as prefix for test case name.</param>
/// <returns>
/// IEnumerable TestCaseData
/// </returns>
/// <exception cref="System.InvalidOperationException">Exception when wrong cell type in file</exception>
/// <exception cref="DataDrivenReadException">Exception when parameter not found in row</exception>
/// <example>How to use it: <code>
/// public static IEnumerable CredentialsFromExcel
/// {
/// get { return DataDrivenHelper.ReadXlsxDataDriveFile(ProjectBaseConfiguration.DataDrivenFileXlsx, "credential", new[] { "user", "password" }, "credentialExcel"); }
/// }
/// </code></example>
public static IEnumerable<TestCaseData> ReadXlsxDataDriveFile(string path, string sheetName, [Optional] string[] diffParam, [Optional] string testName)
{
Logger.Debug("Sheet {0} in file: {1}", sheetName, path);
XSSFWorkbook wb;

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
wb = new XSSFWorkbook(fs);
}

// get sheet
var sh = (XSSFSheet)wb.GetSheet(sheetName);

int startRow = 1;
int startCol = 0;
int totalRows = sh.LastRowNum;
int totalCols = sh.GetRow(0).LastCellNum;

var row = 1;
for (int i = startRow; i <= totalRows; i++, row++)
{
var column = 0;
var testParams = new Dictionary<string, string>();
for (int j = startCol; j < totalCols; j++, column++)
{
if (sh.GetRow(0).GetCell(column).CellType != CellType.String)
{
throw new InvalidOperationException(string.Format("Cell with name of parameter must be string only, file {0} at sheet {1} row {2} column {3}", path, sheetName, 0, column));
}

var cellType = sh.GetRow(row).GetCell(column).CellType;
switch (cellType)
{
case CellType.String:
testParams.Add(sh.GetRow(0).GetCell(column).StringCellValue, sh.GetRow(row).GetCell(column).StringCellValue);
break;
case CellType.Numeric:
testParams.Add(sh.GetRow(0).GetCell(column).StringCellValue, sh.GetRow(row).GetCell(column).NumericCellValue.ToString(CultureInfo.CurrentCulture));
break;
default:
throw new InvalidOperationException(string.Format("Not supported cell type {0} in file {1} at sheet {2} row {3} column {4}", cellType, path, sheetName, row, column));
}
}

// set test name
var testCaseName = string.IsNullOrEmpty(testName) ? sheetName : testName;

if (diffParam != null && diffParam.Any())
{
try
{
testCaseName = TestCaseName(diffParam, testParams, testCaseName);
}
catch (DataDrivenReadException e)
{
throw new DataDrivenReadException(
string.Format(
" Exception while reading Excel Data Driven file\n searched key '{0}' not found at sheet '{1}' \n for test {2} in file '{3}' at row {4}",
e.Message,
sheetName,
testName,
path,
row));
}
}
else
{
testCaseName = testCaseName + "_row(" + row + ")";
}

var data = new TestCaseData(testParams);
data.SetName(testCaseName);
yield return data;
}
}

/// <summary>
/// Get the name of test case from value of parameters.
/// </summary>
Expand Down Expand Up @@ -150,5 +250,5 @@ private static string TestCaseName(string[] diffParam, Dictionary<string, string

return testCaseName;
}
}
}
}
10 changes: 10 additions & 0 deletions Objectivity.Test.Automation.Tests.NUnit/DataDriven/TestData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ public static IEnumerable Credentials
get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "credential", new[] { "user", "password" }, "credential"); }
}

public static IEnumerable CredentialsExcel
{
get { return DataDrivenHelper.ReadXlsxDataDriveFile(ProjectBaseConfiguration.DataDrivenFileXlsx, "credential", new[] { "user", "password" }, "credentialExcel"); }
}

public static IEnumerable LinksSetTestName
{
get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "links", new[] { "number" }, "Count_links"); }
Expand All @@ -43,5 +48,10 @@ public static IEnumerable Links
{
get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "links"); }
}

public static IEnumerable LinksExcel
{
get { return DataDrivenHelper.ReadXlsxDataDriveFile(ProjectBaseConfiguration.DataDrivenFileXlsx, "links"); }
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,30 @@
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<ItemGroup>
<Reference Include="ICSharpCode.SharpZipLib, Version=0.86.0.518, Culture=neutral, PublicKeyToken=1b03e6acf1164f73, processorArchitecture=MSIL">
<HintPath>..\packages\SharpZipLib.0.86.0\lib\20\ICSharpCode.SharpZipLib.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.3.5\lib\net45\NLog.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NPOI, Version=2.3.0.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<HintPath>..\packages\NPOI.2.3.0\lib\net40\NPOI.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NPOI.OOXML, Version=2.3.0.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<HintPath>..\packages\NPOI.2.3.0\lib\net40\NPOI.OOXML.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NPOI.OpenXml4Net, Version=2.3.0.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<HintPath>..\packages\NPOI.2.3.0\lib\net40\NPOI.OpenXml4Net.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NPOI.OpenXmlFormats, Version=2.3.0.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<HintPath>..\packages\NPOI.2.3.0\lib\net40\NPOI.OpenXmlFormats.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="nunit.framework, Version=3.9.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.9.0\lib\net45\nunit.framework.dll</HintPath>
<Private>True</Private>
Expand All @@ -84,6 +104,7 @@
<SubType>Code</SubType>
</Compile>
<Compile Include="Tests\CompareFilesDataDrivenTests.cs" />
<Compile Include="Tests\HerokuappTestsDataDrivenNUnit.cs" />
<Compile Include="Tests\HerokuappTestsNUnit.cs" />
<Compile Include="Tests\JavaScriptAlertsTestsNUnit.cs" />
<Compile Include="Tests\PerformanceTestsNUnit.cs" />
Expand All @@ -94,6 +115,9 @@
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="DataDriven\DataDriven.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="NLog.xsd">
<SubType>Designer</SubType>
</None>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,25 @@ public static string DataDrivenFile
}
}

/// <summary>
/// Gets the Excel data driven file.
/// </summary>
/// <value>
/// The Excel data driven file.
/// </value>
public static string DataDrivenFileXlsx
{
get
{
if (BaseConfiguration.UseCurrentDirectory)
{
return Path.Combine(CurrentDirectory + ConfigurationManager.AppSettings["DataDrivenFileXlsx"]);
}

return ConfigurationManager.AppSettings["DataDrivenFileXlsx"];
}
}

/// <summary>
/// Gets the Download Folder path
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// <copyright file="HerokuappTestsDataDrivenNUnit.cs" company="Objectivity Bespoke Software Specialists">
// Copyright (c) Objectivity Bespoke Software Specialists. All rights reserved.
// </copyright>
// <license>
// The MIT License (MIT)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </license>

namespace Objectivity.Test.Automation.Tests.NUnit.Tests
{
using System.Collections.Generic;
using Automation.Tests.PageObjects.PageObjects.TheInternet;
using Common;
using DataDriven;
using global::NUnit.Framework;

[TestFixture]
[Parallelizable(ParallelScope.Fixtures)]
public class HerokuappTestsDataDrivenNUnit : ProjectTestBase
{
[Test]
[TestCaseSource(typeof(TestData), "Credentials")]
public void FormAuthenticationPageTest(IDictionary<string, string> parameters)
{
new InternetPage(this.DriverContext).OpenHomePage().GoToFormAuthenticationPage();

var formFormAuthentication = new FormAuthenticationPage(this.DriverContext);
formFormAuthentication.EnterUserName(parameters["user"]);
formFormAuthentication.EnterPassword(parameters["password"]);
formFormAuthentication.LogOn();
Verify.That(
this.DriverContext,
() => Assert.AreEqual(parameters["message"], formFormAuthentication.GetMessage));
}

[Test]
[TestCaseSource(typeof(TestData), "CredentialsExcel")]
public void FormAuthenticationPageExcelTest(IDictionary<string, string> parameters)
{
new InternetPage(this.DriverContext).OpenHomePage().GoToFormAuthenticationPage();

var formFormAuthentication = new FormAuthenticationPage(this.DriverContext);
formFormAuthentication.EnterUserName(parameters["user"]);
formFormAuthentication.EnterPassword(parameters["password"]);
formFormAuthentication.LogOn();
Verify.That(
this.DriverContext,
() => Assert.AreEqual(parameters["message"], formFormAuthentication.GetMessage));
}

[Test]
[Category("PhantomJs")]
[TestCaseSource(typeof(TestData), "LinksSetTestName")]
public void CountLinksAndSetTestNameAtShiftingContentTest(IDictionary<string, string> parameters)
{
new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

var links = new ShiftingContentPage(this.DriverContext);
Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
}

[Test]
[TestCaseSource(typeof(TestData), "LinksExcel")]
public void CountLinksAndSetTestNameAtShiftingContentExcelTest(IDictionary<string, string> parameters)
{
new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

var links = new ShiftingContentPage(this.DriverContext);
Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
}

[Test]
[TestCaseSource(typeof(TestData), "Links")]
public void CountLinksAtShiftingContentTest(IDictionary<string, string> parameters)
{
new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

var links = new ShiftingContentPage(this.DriverContext);
Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,6 @@ public void BasicAuthTest()
basicAuthPage.GetCongratulationsInfo));
}

[Test]
[TestCaseSource(typeof(TestData), "Credentials")]
public void FormAuthenticationPageTest(IDictionary<string, string> parameters)
{
new InternetPage(this.DriverContext).OpenHomePage().GoToFormAuthenticationPage();

var formFormAuthentication = new FormAuthenticationPage(this.DriverContext);
formFormAuthentication.EnterUserName(parameters["user"]);
formFormAuthentication.EnterPassword(parameters["password"]);
formFormAuthentication.LogOn();
Verify.That(
this.DriverContext,
() => Assert.AreEqual(parameters["message"], formFormAuthentication.GetMessage));
}

[Test]
public void ForgotPasswordTest()
{
Expand All @@ -74,27 +59,6 @@ public void ForgotPasswordTest()
() => Assert.AreEqual("Your e-mail's been sent!", forgotPassword.ClickRetrievePassword));
}

[Test]
[Category("PhantomJs")]
[TestCaseSource(typeof(TestData), "LinksSetTestName")]
public void CountLinksAndSetTestNameAtShiftingContentTest(IDictionary<string, string> parameters)
{
new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

var links = new ShiftingContentPage(this.DriverContext);
Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
}

[Test]
[TestCaseSource(typeof(TestData), "Links")]
public void CountLinksAtShiftingContentTest(IDictionary<string, string> parameters)
{
new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

var links = new ShiftingContentPage(this.DriverContext);
Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
}

[Test]
[Category("PhantomJs")]
public void MultipleWindowsTest()
Expand Down

0 comments on commit ae935e2

Please sign in to comment.