From ebf026a20ad3287355e8a52e26ed6a14ea86b2ef Mon Sep 17 00:00:00 2001 From: Sirajuddin Khan Date: Thu, 1 Feb 2024 19:14:13 +0530 Subject: [PATCH] Add files via upload --- README.md | 223 +++++++++++++++++++++++ XUnit-LambdaTest.sln | 25 +++ XUnit-LambdaTest/BaseFixture.cs | 104 +++++++++++ XUnit-LambdaTest/ParallelTest.cs | 101 ++++++++++ XUnit-LambdaTest/SingleTest.cs | 66 +++++++ XUnit-LambdaTest/XUnit-LambdaTest.csproj | 26 +++ XUnit-LambdaTest/config.json | 27 +++ 7 files changed, 572 insertions(+) create mode 100644 README.md create mode 100644 XUnit-LambdaTest.sln create mode 100644 XUnit-LambdaTest/BaseFixture.cs create mode 100644 XUnit-LambdaTest/ParallelTest.cs create mode 100644 XUnit-LambdaTest/SingleTest.cs create mode 100644 XUnit-LambdaTest/XUnit-LambdaTest.csproj create mode 100644 XUnit-LambdaTest/config.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..e0fa994 --- /dev/null +++ b/README.md @@ -0,0 +1,223 @@ +# Run Selenium Tests With xUnit On LambdaTest + +![LambdaTest Logo](https://user-images.githubusercontent.com/70570645/171429042-610e8f3d-d2a4-4896-8bdb-8aeed87e0ce7.png) + +*Learn how to run C# scripts using the xUnit framework.* + +

+ Blog +   ⋅   + Docs +   ⋅   + Learning Hub +   ⋅   + Newsletter +   ⋅   + Certifications +   ⋅   + YouTube +

+  +  +  + +[](https://accounts.lambdatest.com/register) + +## Table of Contents: + +* [Prerequisites](#prerequisites) +* [Run Your First Test](#run-your-first-test) +* [Parallel Testing With xUnit](#running-your-parallel-tests-using-xunit-testing-framework) +* [Local Testing With xUnit](#testing-locally-hosted-or-privately-hosted-projects) + +## Prerequisites + +Before you start performing **C#** automation testing with **Selenium** using xUnit, you need to: + +* Download and install **Selenium WebDriver** from its [official website](https://www.selenium.dev/downloads/). +* Ensure you have the latest version of C#. +* **.NET** framework for guidelines while developing a range of applications using C#. +* Download [Selenium WebDriver Language Binding](https://www.selenium.dev/downloads/) for C# and extract them to the appropriate folder. Require a [.NET Core SDK](https://dotnet.microsoft.com/en-us/download) of 8.0 or greater version. + +### Installing Selenium Dependencies And Tutorial Repo + +**Step 1:** Clone the LambdaTest CSharp-xUnit-Selenium GitHub repository and navigate to the code directory: + +``` +git clone https://github.com/LambdaTest/CSharp-xUnit-Selenium +cd CSharp-xUnit-Selenium +``` + +### Setting up Your Authentication + +Ensure you have your LambdaTest credentials to run C# automation scripts. Obtain these credentials from the [LambdaTest Automation Dashboard](https://automation.lambdatest.com/login) or your LambdaTest Profile. + +**Step 2:** Set your LambdaTest Username and Access Key in environment variables. + +**For Linux/macOS:** + +``` sh +export LT_USERNAME="YOUR_USERNAME" +export LT_ACCESS_KEY="YOUR_ACCESS_KEY" +``` + +**For Windows:** + +```sh +set LT_USERNAME="YOUR_USERNAME" +set LT_ACCESS_KEY="YOUR_ACCESS_KEY" +``` + +## Run Your First Test + +> **Test Scenario**: Check out the sample SingleTest.cs file. This xUnit Selenium script tests a sample to-do list app by marking a couple of items as done, adding a new item to the list, and finally displaying the count of pending items as output. + +**Step 3:** Navigate to [config.json](https://github.com/LambdaTest/CSharp-xUnit-Selenium/blob/master/xUnitSelenium/config.json) using VSCode. Replace this code in the config.json file in your project. + +### Configuration of Your Test Capabilities + +**Step 4:** In the config, update your test capabilities. We are passing browser, browser version, and operating system information, along with LambdaTest Selenium grid capabilities via the capabilities object. + +Example capabilities object: + + +```json +{ + "server": "hub.lambdatest.com", + "user": "LT_USERNAME", + "key": "LT_ACCESS_KEY", + + "capabilities": { + "lt:options": { + "buildName": "xunit build", + "sessionName": "lambdatest xunit sample test", + "visual": "true", + "plugin": "xunit:sample" + } + }, + + "environments": [ + { + "browserName": "chrome" + }, + { + "browserName": "firefox" + }, + { + "browserName": "safari" + } + ], + + "TunnelOptions": { + "tunnel": false + } +} + +``` + +**Note:** Generate capabilities for your test requirements with the help of the **[Desired Capability Generator](https://www.lambdatest.com/capabilities-generator/)**. + +### Executing the Test + +**Step 5:** Build the solution in Visual Studio. + +**Step 6:** Run the + + tests from the Test Explorer in Visual Studio. + +### Executing in Linux/macOS + +* Clean and rebuild the project. + +```sh +dotnet clean +``` +* Execute Single Test + +```sh +dotnet test --filter "profile=single" +``` + +## Running Your Parallel Tests Using xUnit Testing Framework + +**Executing Parallel tests in Windows** + +Run all tests from the Test Explorer in Visual Studio for parallel execution. + +**Executing parallel tests in Linux/MacOS** + +```sh +dotnet test --filter "profile=parallel" +``` + +## Testing Locally Hosted Or Privately Hosted Projects + +For testing locally hosted or privately hosted projects with LambdaTest Selenium grid using LambdaTest Tunnel, follow the [LambdaTest Tunnel documentation](https://www.lambdatest.com/support/docs/testing-locally-hosted-pages/). + +Download the LambdaTest Tunnel binary for your OS and run the following command: + +```bash +LT -user {user’s login email} -key {user’s access key} +``` + +**Tunnel Capability** + +```json +"lt:options": { + "buildName": "xunit build", + "sessionName": "lambdatest xunit sample test", + "visual": "true", + "plugin": "xunit:sample", + "tunnel": "true" + } +``` + +## Tutorials 📙 + +*coming soon* + +Subscribe To Our [LambdaTest YouTube Channel 🔔](https://www.youtube.com/c/LambdaTest) for the latest video tutorials. + +## Documentation & Resources :books: + +* [LambdaTest Documentation](https://www.lambdatest.com/support/docs/) +* [LambdaTest Blog](https://www.lambdatest.com/blog/) +* [LambdaTest Learning Hub](https://www.lambdatest.com/learning-hub/) + +## LambdaTest Community :busts_in_silhouette: + +Join the [LambdaTest Community](https://community.lambdatest.com/) to interact with tech enthusiasts. Connect, ask questions, and learn from professionals worldwide. + +## What's New At LambdaTest ❓ + +Stay updated with the latest features and product add-ons at [Changelog](https://changelog.lambdatest.com/). + +## About LambdaTest + +[LambdaTest](https://www.lambdatest.com/) is a leading test execution and orchestration platform. It allows users to run both manual and automated testing of web and mobile apps across various browsers, operating systems, and real device combinations. Over 500 enterprises and 1 million+ users across 130+ countries rely on LambdaTest for their testing needs. + +### Features + +* Run Selenium, Cypress, Puppeteer, Playwright, and Appium automation tests across 3000+ real desktop and mobile environments. +* Real-time Cross-browser testing on 3000+ environments. +* Test on Real device cloud. +* Blazing fast test automation with HyperExecute. +* Accelerate testing, shorten job times, and get faster feedback on code changes with Test At Scale. +* Smart Visual Regression Testing on the cloud. +* 120+ third-party integration with your favorite tools for CI/CD, Project Management, Codeless Automation, and more. +* Automated Screenshot testing across multiple browsers in a single click. +* Local testing of web and mobile apps. +* Online Accessibility Testing across 3000+ desktop and mobile browsers, browser versions, and operating systems. +* Geolocation testing of web and mobile apps across 53+ countries. +* LT Browser - for responsive testing across 50+ pre-installed mobile, tablets, desktop, and laptop viewports. + +[](https://accounts.lambdatest.com/register) + +## We Are Here to Help You :headphones: + +* Have a query? We are available 24x7 to help. [Contact Us](mailto:support@lambdatest.com) +* For more info, visit [LambdaTest](https://www.lambdatest.com/) + + diff --git a/XUnit-LambdaTest.sln b/XUnit-LambdaTest.sln new file mode 100644 index 0000000..23df77f --- /dev/null +++ b/XUnit-LambdaTest.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32616.157 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XUnit-LambdaTest", "XUnit-LambdaTest\XUnit-LambdaTest.csproj", "{E4CB1B19-9253-4E1C-876C-1A13922E2404}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E4CB1B19-9253-4E1C-876C-1A13922E2404}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4CB1B19-9253-4E1C-876C-1A13922E2404}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E4CB1B19-9253-4E1C-876C-1A13922E2404}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E4CB1B19-9253-4E1C-876C-1A13922E2404}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {896D0BC3-8440-4DF8-9415-5FDDE5C36200} + EndGlobalSection +EndGlobal diff --git a/XUnit-LambdaTest/BaseFixture.cs b/XUnit-LambdaTest/BaseFixture.cs new file mode 100644 index 0000000..480240f --- /dev/null +++ b/XUnit-LambdaTest/BaseFixture.cs @@ -0,0 +1,104 @@ +using OpenQA.Selenium.Remote; +using Newtonsoft.Json.Linq; +using OpenQA.Selenium.Remote; +using OpenQA.Selenium; + +namespace XUnit_LambdaTest +{ + public class BaseFixture : IDisposable + { + + private RemoteWebDriver? WebDriver; + + + public RemoteWebDriver GetDriver(string platform, string profile) + { + // Get Configuration for correct profile + string currentDirectory = Directory.GetCurrentDirectory(); + string path = Path.Combine(currentDirectory, "config.json"); + JObject config = JObject.Parse(File.ReadAllText(path)); + if (config is null) + throw new Exception("Configuration not found!"); + + // Get Platform specific capabilities + JObject capabilities = config.GetValue("environments").Where(x => x is JObject y && x["browserName"].ToString().Equals(platform)).ToList()[0] as JObject; + + // Get Common Capabilities + JObject commonCapabilities = config.GetValue("capabilities") as JObject; + + // Merge Capabilities + capabilities.Merge(commonCapabilities); + + JObject ltOptions = capabilities["lt:options"] as JObject; + + // Get username and accesskey + string? username = Environment.GetEnvironmentVariable("LT_USERNAME"); + if (username is null) + username = config.GetValue("user").ToString(); + + string? accessKey = Environment.GetEnvironmentVariable("LT_ACCESS_KEY"); + if (accessKey is null) + accessKey = config.GetValue("key").ToString(); + + ltOptions["userName"] = username; + ltOptions["accessKey"] = accessKey; + + + + capabilities["lt:options"] = ltOptions; + + // Create Desired Cappabilities for WebDriver + DriverOptions desiredCapabilities = getBrowserOption(capabilities.GetValue("browserName").ToString()); + capabilities.Remove("browserName"); + foreach (var x in capabilities) + { + if (x.Key.Equals("lt:options")) + desiredCapabilities.AddAdditionalOption(x.Key, x.Value.ToObject>()); + else + desiredCapabilities.AddAdditionalOption(x.Key, x.Value); + } + + // Create RemoteWebDriver instance + WebDriver = new RemoteWebDriver(new Uri($"https://{config["server"]}/wd/hub"), desiredCapabilities); + + return WebDriver; + } + + public void SetStatus(bool passed) + { + if(WebDriver is not null) + { + if (passed) + ((IJavaScriptExecutor)WebDriver).ExecuteScript("lambda-status=passed"); + else + ((IJavaScriptExecutor)WebDriver).ExecuteScript("lambda-status=failed"); + } + } + + static DriverOptions getBrowserOption(String browser) + { + switch (browser) + { + case "chrome": + return new OpenQA.Selenium.Chrome.ChromeOptions(); + case "firefox": + return new OpenQA.Selenium.Firefox.FirefoxOptions(); + case "safari": + return new OpenQA.Selenium.Safari.SafariOptions(); + case "edge": + return new OpenQA.Selenium.Edge.EdgeOptions(); + default: + return new OpenQA.Selenium.Chrome.ChromeOptions(); + } + } + + public void Dispose() + { + if (WebDriver is not null) + { + WebDriver.Quit(); + WebDriver.Dispose(); + } + } + } +} diff --git a/XUnit-LambdaTest/ParallelTest.cs b/XUnit-LambdaTest/ParallelTest.cs new file mode 100644 index 0000000..c54c9db --- /dev/null +++ b/XUnit-LambdaTest/ParallelTest.cs @@ -0,0 +1,101 @@ +using Xunit; +using OpenQA.Selenium; +using OpenQA.Selenium.Remote; +using OpenQA.Selenium.Support.UI; + +namespace XUnit_LambdaTest +{ + public abstract class ParallelBaseTest + { + private readonly BaseFixture baseFixture; + + public ParallelBaseTest(BaseFixture baseFixture) + { + this.baseFixture = baseFixture; + } + + public void BaseTest(string platform) + { + try + { + RemoteWebDriver driver = baseFixture.GetDriver(platform, "parallel"); + WebDriverWait webDriverWait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(2000)); + driver.Manage().Window.Maximize(); + driver.Navigate().GoToUrl("https://lambdatest.github.io/sample-todo-app/"); + + + Assert.Equal("Sample page - lambdatest.com", driver.Title); + // Click on First Check box + IWebElement firstCheckBox = driver.FindElement(By.Name("li1")); + firstCheckBox.Click(); + + // Click on Second Check box + IWebElement secondCheckBox = driver.FindElement(By.Name("li2")); + secondCheckBox.Click(); + + // Enter Item name + IWebElement textfield = driver.FindElement(By.Id("sampletodotext")); + + String itemName = "Yey, Let's add it to list"; + textfield.SendKeys(itemName); + + // Click on Add button + IWebElement addButton = driver.FindElement(By.Id("addbutton")); + addButton.Click(); + + // Verified Added Item name + IWebElement itemtext = driver.FindElement(By.XPath("/html/body/div/div/div/ul/li[6]/span")); + String getText = itemtext.Text; + Assert.True(itemName.Contains(getText)); + + /* Perform wait to check the output */ + System.Threading.Thread.Sleep(2000); + + Console.WriteLine("LT_ToDo_Test Passed"); + baseFixture.SetStatus(true); + } + catch (Exception) + { + baseFixture.SetStatus(false); + throw; + } + } + } + + public class ChromeTest : ParallelBaseTest, IClassFixture + { + public ChromeTest(BaseFixture baseFixture) : base(baseFixture) { } + + [Fact] + [Trait("profile", "parallel")] + public void Test() + { + BaseTest("chrome"); + } + } + + public class FirefoxTest : ParallelBaseTest, IClassFixture + { + public FirefoxTest(BaseFixture baseFixture) : base(baseFixture) { } + + [Fact] + [Trait("profile", "parallel")] + public void Test() + { + BaseTest("firefox"); + } + } + + public class SafariTest : ParallelBaseTest, IClassFixture + { + public SafariTest(BaseFixture baseFixture) : base(baseFixture) { } + + [Fact] + [Trait("profile", "parallel")] + public void Test() + { + BaseTest("safari"); + } + } + +} diff --git a/XUnit-LambdaTest/SingleTest.cs b/XUnit-LambdaTest/SingleTest.cs new file mode 100644 index 0000000..15e54b2 --- /dev/null +++ b/XUnit-LambdaTest/SingleTest.cs @@ -0,0 +1,66 @@ +using Xunit; +using OpenQA.Selenium; +using OpenQA.Selenium.Remote; +using OpenQA.Selenium.Support.UI; + +namespace XUnit_LambdaTest +{ + public class SingleTest : IClassFixture + { + + private readonly BaseFixture baseFixture; + + public SingleTest(BaseFixture baseFixture) + { + this.baseFixture = baseFixture; + } + + [Fact] + [Trait("profile", "single")] + public void Test() + { + try + { + RemoteWebDriver driver = baseFixture.GetDriver("chrome", "single"); + WebDriverWait webDriverWait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(2000)); + driver.Manage().Window.Maximize(); + driver.Navigate().GoToUrl("https://lambdatest.github.io/sample-todo-app/"); + + Assert.Equal("Sample page - lambdatest.com", driver.Title); + // Click on First Check box + IWebElement firstCheckBox = driver.FindElement(By.Name("li1")); + firstCheckBox.Click(); + + // Click on Second Check box + IWebElement secondCheckBox = driver.FindElement(By.Name("li2")); + secondCheckBox.Click(); + + // Enter Item name + IWebElement textfield = driver.FindElement(By.Id("sampletodotext")); + + String itemName = "Yey, Let's add it to list"; + textfield.SendKeys(itemName); + + // Click on Add button + IWebElement addButton = driver.FindElement(By.Id("addbutton")); + addButton.Click(); + + // Verified Added Item name + IWebElement itemtext = driver.FindElement(By.XPath("/html/body/div/div/div/ul/li[6]/span")); + String getText = itemtext.Text; + Assert.True(itemName.Contains(getText)); + + /* Perform wait to check the output */ + System.Threading.Thread.Sleep(2000); + + Console.WriteLine("LT_ToDo_Test Passed"); + baseFixture.SetStatus(true); + } + catch (Exception) + { + baseFixture.SetStatus(false); + throw; + } + } + } +} diff --git a/XUnit-LambdaTest/XUnit-LambdaTest.csproj b/XUnit-LambdaTest/XUnit-LambdaTest.csproj new file mode 100644 index 0000000..bd09e84 --- /dev/null +++ b/XUnit-LambdaTest/XUnit-LambdaTest.csproj @@ -0,0 +1,26 @@ + + + + net8.0 + XUnit_LambdaTest + enable + enable + + false + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + Always + + + + diff --git a/XUnit-LambdaTest/config.json b/XUnit-LambdaTest/config.json new file mode 100644 index 0000000..35d4cae --- /dev/null +++ b/XUnit-LambdaTest/config.json @@ -0,0 +1,27 @@ +{ + "server": "hub.lambdatest.com", + "user": "LT_USERNAME", + "key": "LT_ACCESS_KEY", + + "capabilities": { + "lt:options": { + "buildName": "xunit build", + "sessionName": "lambdatest xunit sample test", + "visual": "true", + "plugin": "xunit:sample", + "tunnel": "false" + } + }, + + "environments": [ + { + "browserName": "chrome" + }, + { + "browserName": "firefox" + }, + { + "browserName": "safari" + } + ] +}