How can I integrate selenium tests with sauce labs in c#? - c#

On saucelabs website they provide a code snippet like this:
WebDriver webDriver = new WebDriver();
webDriver.set(new RemoteWebDriver(
new URL("https://UrlHEREagwgwgqwg4894+4+91gwgq")
))
When I add this to my tests, under WebDriver it says type or namespace 'WebDriver' could not be found. It is coming up for a namespace. For my Selenium tests I am using IWebDriver. I tried to change the WebDriver to IWebDriver and that didn't work. I also get the same error under the URL saying the namespace could not be found. For that one it does show for a namespace using System.Security.Policy; If I add that then I get an error under
new URL("https://UrlHEREagwgwgqwg4894+4+91gwgq")
Argument 1: cannot convert from 'System.Security.Policy.Url' to 'OpenQA.Selenium.DriverOptions'
This is how I am trying to use it. I was using ChromeDriver for my selenium tests but commented that part out to test on other browsers with saucelabs. This is my first time working with selenium/saucelabs so what I am doing my be completely off and I appreciate any advice.
[Fact]
public static void ClickDownloadButton()
{
WebDriver driver = new WebDriver();
driver.set(new RemoteWebDriver(
new Url("https://UrlHEREagwgwgqwg4894+4+91gwgq")
));
//using IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl(BaseUrl.downloadsUrl);
var login = new Login(driver);
login.EnterEmail();
login.EnterPassword();
login.HitSubmit();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
var downloadButton = wait.Until((d) => d.FindElements(By.LinkText("Download File")));
foreach (var button in downloadButton)
{
IWebElement element = wait.Until((d) => d.FindElement(By.LinkText("Download File")));
element.Click();
}
driver.Quit();
}
Here are the using statements:
using Xunit;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Security.Policy;
using OpenQA.Selenium.Remote;

Check out our demo C# repository with tons of examples.
Here's a working example that you can use from the following file:
using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
namespace Selenium3.Nunit.Scripts.SimpleExamples
{
[TestFixture]
[Category("SimpleTest")]
public class SimpleSauceTest
{
IWebDriver _driver;
[Test]
public void SimpleTest()
{
//TODO please supply your Sauce Labs user name in an environment variable
var sauceUserName = Environment.GetEnvironmentVariable(
"SAUCE_USERNAME", EnvironmentVariableTarget.User);
//TODO please supply your own Sauce Labs access Key in an environment variable
var sauceAccessKey = Environment.GetEnvironmentVariable(
"SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability(CapabilityType.Version, "latest", true);
options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
options.AddAdditionalCapability("username", sauceUserName, true);
options.AddAdditionalCapability("accessKey", sauceAccessKey, true);
options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);
options.AddAdditionalCapability("build", "ShwabTeamName:" + DateTime.Now, true);
_driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"), options.ToCapabilities(),
TimeSpan.FromSeconds(600));
_driver.Navigate().GoToUrl("https://www.google.com");
Assert.Pass();
}
[TearDown]
public void CleanUpAfterEveryTestMethod()
{
var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
}
}
Don't forget to install the correct Nuget packages so you have the corresponding resources. This is the minimum that you'll need:
<package id="Selenium.Support" />
<package id="Selenium.WebDriver" />
Side Note:
Don't use static methods as it'll make it impossible for you to parallelize.

Related

Cant Launch a window with Selenium Chrome Driver c#

Environment:
Vs2019, C#
NuGet Package: Selenium v3.141.0 by Selenium Committee.
Chrome Driver from Selenium website - v92.0
IWebDriver Driver = new ChromeDriver("FolderPath"); //time out error here.
Driver.url = "www.google.com"
with no other code, I can't get pass declaring Chrome Driver. I get a time out error with local host.
I tried:
setting a different port.
adding "no-sandbox" to arguments.
I would try utilizing the ChromeDriver NuGet package instead of pointing to a local file location
https://www.nuget.org/packages/Selenium.WebDriver.ChromeDriver/
Here is a simple example for you to reference
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace ExampleDemo
{
[TestFixture]
public class Chrome_test
{
private IWebDriver driver;
[Test(Description="Go To Google")]
public void GoToGoogle() {
homeURL = https://www.google.com/;
driver.Navigate().GoToUrl(homeURL);
}
[TearDown]
public void TearDownTest()
{
driver.Close();
}
[SetUp]
public void SetupTest()
{
driver = new ChromeDriver();
}
}
}
I need to add a chrome option:
ChromeOptions options = new ChromeOptions()
options.add("--remote-debugging-port=9222 ") // change port if necessary

C# Selenium bot element selection trouble

I am trying to make a bot that goes through drop-downs and makes selections but it's having trouble finding the element. The code is below.
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.Extensions;
using OpenQA.Selenium.Support.UI;
namespace selenium_test
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver;
driver = new ChromeDriver("C:\\");
Console.WriteLine("ChromeDriver Initialized");
driver.Url = "https://odyssey.gwinnettcourts.com/Portal/Home/Dashboard/26";
IWebElement typeElement = driver.FindElement(By.XPath(".//option[#id='cboHSSearchBy']"));
var typeSelect = new SelectElement(typeElement);
typeSelect.SelectByValue("JudicialOfficer");
typeElement.Click();
}
}
}
what exactly is the error? I can only assume that it is taking time to find element.
add wait time maybe? also, why using xpath when you have id of controls? id is quicker!
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists((By.Id("cboHSSearchBy"))));

addScriptToEvaluateOnNewDocument Selenium (Does not work)

I need to execute addScriptToEvaluateOnNewDocument method of Google Headless Chrome in C# .Net. I basically need to execute Javascript before any other javascript is executed on the documents. Here is my code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
namespace User
{
class Program
{
//public static IWebDriver driver = new ChromeDriver();
public static IWebDriver driver;
public static double magnification = 2;
static void Main(string[] args)
{
ChromeOptions options = new ChromeOptions();
//options.AddArgument("Page.addScriptToEvaluateOnNewDocument");
options.AddArgument("--window-size=1920,1080");
options.AddUserProfilePreference("Page.addScriptToEvaluateOnNewDocument", "alert('INJECTED SCRIPT')");
driver = new ChromeDriver(options);
var action = new OpenQA.Selenium.Interactions.Actions(driver);
System.Threading.Thread.Sleep(1000);
driver.Navigate().GoToUrl("https://google.com");
System.Threading.Thread.Sleep(10000);
}
}
}
But the alert isn't fired (i have tried other JavaScript code besides alert - nothing seems to work)
Try this.After initialize the driver.Hope this will work.
driver.ExecuteJavaScript("alert(0);")
OR
driver.Scripts().ExecuteScript("alert(0);")
I have only done this in Python but it should work the same way.
The chromedriver should expose a function named execute_cdp_cmd()
You can use this to run JavaScript before the page JavaScript is run. See the python example below. Note that you should add the code shown below after creating the driver but before you get the web page.
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
alert(0);
"""
})
I don't have a C# example, but this might help.
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.DevTools.V91.Page;
using OpenQA.Selenium.Support.UI;
using RandomNameGeneratorLibrary;
using Network = OpenQA.Selenium.DevTools.V91.Network;
using DevToolsSessionDomains = OpenQA.Selenium.DevTools.V91.DevToolsSessionDomains;
IDevTools devTools = driver as IDevTools;
session = devTools.GetDevToolsSession();
var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
domains.Page.AddScriptToEvaluateOnNewDocument(new AddScriptToEvaluateOnNewDocumentCommandSettings()
{
Source = jscode,
});

Getting an Exception System.ComponentModel.Win32Exception : The system cannot find the file specified in Sikuli C#

I am getting an exception System.ComponentModel.Win32Exception : The system cannot find the file specified when i employ Sikuli in C# using selenium.
I have referred to other posts in Stack but i have not not got a solution for that.
I am also running VS 2017 in administrator mode
I have latest copy of Rest-Api Jar in /Debug folder.
Below is my code
using System;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using Sikuli4Net.sikuli_REST;
using Sikuli4Net.sikuli_UTIL;
using SikuliModule;
namespace DownloadFile
{
public class Download
{
private IWebDriver driver;
private APILauncher launcher;
[SetUp]
public void setup()
{
driver = new FirefoxDriver();
launcher = new APILauncher(true);
driver.Navigate().GoToUrl("https://java.com/en/download/");
driver.Manage().Window.Maximize();
}
[Test]
public void TestMethod1()
{
new WebDriverWait(driver, TimeSpan.FromSeconds(60)).Until(ExpectedConditions.ElementExists((By.XPath("//span[contains(text(),'Free Java Download')]")))).Click();
new WebDriverWait(driver, TimeSpan.FromSeconds(60)).Until(ExpectedConditions.ElementExists((By.XPath("//span[contains(text(),'Agree and Start Free Download')]")))).Click();
launcher.Start();
Screen screen = new Screen();
Pattern Click_Save = new Pattern("C:/Selenium Files/Save.jpg");
screen.Wait(Click_Save, 500);
screen.Click(Click_Save);
launcher.Stop();
}
}
}
Update your path of .jpg file in below line of code:
Pattern Click_Save = new Pattern("C:\\Selenium Files\\Save.jpg");
Rest of the code seems fine.

How do I use Selenium in C#?

Selenium.
I downloaded the C# client drivers and the IDE. I managed to record some tests and successfully ran them from the IDE. But now I want to do that using C#. I added all relevant DLL files (Firefox) to the project, but I don't have the Selenium class. Some Hello, World! would be nice.
From the Selenium Documentation:
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
class GoogleSuggest
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.google.com/");
IWebElement query = driver.FindElement(By.Name("q"));
query.SendKeys("Cheese");
System.Console.WriteLine("Page title is: " + driver.Title);
driver.Quit();
}
}
Install the NuGet packet manager
Download link: https://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c
Create a C# console application
Right-click on the project → Manage NuGet Packages.
Search for "Selenium" and install package Selenium.Support.
You are done now, and you are ready to write your code :)
For code with Internet Explorer, download the Internet Explorer driver.
Link: http://selenium-release.storage.googleapis.com/index.html
Open 2.45 as its the latest release
Download IEDriverServer_x64_2.45.0.zip or IEDriverServer_Win32_2.45.0.zip
Extract and simply paste the .exe file at any location, for example C:\
Remember the path for further use.
Overall reference link: Selenium 2.0 WebDriver with Visual Studio, C#, & IE – Getting Started
My sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;
namespace Selenium_HelloWorld
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver("C:\\");
driver.Navigate().GoToUrl("http://108.178.174.137");
driver.Manage().Window.Maximize();
driver.FindElement(By.Id("inputName")).SendKeys("apatra");
driver.FindElement(By.Id("inputPassword")).SendKeys("asd");
driver.FindElement(By.Name("DoLogin")).Click();
string output = driver.FindElement( By.XPath(".//*[#id='tab-general']/div/div[2]/div[1]/div[2]/div/strong")).Text;
if (output != null )
{
Console.WriteLine("Test Passed :) ");
}
else
{
Console.WriteLine("Test Failed");
}
}
}
}
To set up the IDE for Selenium in conjunction with C# is to use Visual Studio Express. And you can use NUnit as the testing framework. The below links provide you more details. It seems you have set up what is explained in the first link. So check the second link for more details on how to create a basic script.
How to setup C#, NUnit and Selenium client drivers on Visual Studio Express for Automated tests
Creating a basic Selenium web driver test case using NUnit and C#
Sample code from the above blog post:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// Step a
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using NUnit.Framework;
namespace NUnitSelenium
{
[TestFixture]
public class UnitTest1
{
[SetUp]
public void SetupTest()
{
}
[Test]
public void Test_OpeningHomePage()
{
// Step b - Initiating webdriver
IWebDriver driver = new FirefoxDriver();
// Step c: Making driver to navigate
driver.Navigate().GoToUrl("http://docs.seleniumhq.org/");
// Step d
IWebElement myLink = driver.FindElement(By.LinkText("Download"));
myLink.Click();
// Step e
driver.Quit();
)
}
}
One of the things that I had a hard time finding was how to use PageFactory in C#. Especially for multiple IWebElements. If you wish to use PageFactory, here are a few examples. Source: PageFactory.cs
To declare an HTML WebElement, use this inside the class file.
private const string _ID ="CommonIdinHTML";
[FindsBy(How = How.Id, Using = _ID)]
private IList<IWebElement> _MultipleResultsByID;
private const string _ID2 ="IdOfElement";
[FindsBy(How = How.Id, Using = _ID2)]
private IWebElement _ResultById;
Don't forget to instantiate the page object elements inside the constructor.
public MyClass(){
PageFactory.InitElements(driver, this);
}
Now you can access that element in any of your files or methods. Also, we can take relative paths from those elements if we ever wish to. I prefer pagefactory because:
I don't ever need to call the driver directly using driver.FindElement(By.Id("id"))
The objects are lazy initialized
I use this to write my own wait-for-elements methods, WebElements wrappers to access only what I need to expose to the test scripts, and helps keeps things clean.
This makes life a lot easier if you have dynamic (autogerated) webelements like lists of data. You simply create a wrapper that will take the IWebElements and add methods to find the element you are looking for.
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(#"D:\DownloadeSampleCode\WordpressAutomation\WordpressAutomation\Selenium", "geckodriver.exe");
service.Port = 64444;
service.FirefoxBinaryPath = #"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
Instance = new FirefoxDriver(service);
C#
First of all, download Selenium IDE for Firefox from the Selenium IDE.
Use and play around with it, test a scenario, record the steps, and then export it as a C# or Java project as per your requirement.
The code file contains code something like:
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
// Add this name space to access WebDriverWait
using OpenQA.Selenium.Support.UI;
namespace MyTest
{
[TestClass]
public class MyTest
{
public static IWebDriver Driver = null;
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
try
{
string path = Path.GetFullPath(""); // Copy the Chrome driver to the debug
// folder in the bin or set path accordingly
Driver = new ChromeDriver(path);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyCleanup()
{
Driver.Quit();
}
[TestMethod]
public void MyTestMethod()
{
try
{
string url = "http://www.google.com";
Driver.Navigate().GoToUrl(url);
IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30.00)); // Wait in Selenium
wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath(#"//*[#id='lst - ib']")));
var txtBox = Driver.FindElement(By.XPath(#"//*[#id='lst - ib']"));
txtBox.SendKeys("Google Office");
var btnSearch = Driver.FindElement(By.XPath("//*[#id='tsf']/div[2]/div[3]/center/input[1]"));
btnSearch.Click();
System.Threading.Thread.Sleep(5000);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
}
You need to get the Chrome driver from here.
You need to get NuGet packages and necessary DLL files for the Selenium NuGet website.
You need to understand the basics of Selenium from the Selenium documentation website.
That's all...
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using SeleniumAutomationFramework.CommonMethods;
using System.Text;
[TestClass]
public class SampleInCSharp
{
public static IWebDriver driver = Browser.CreateWebDriver(BrowserType.chrome);
[TestMethod]
public void SampleMethodCSharp()
{
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
driver.Url = "http://www.store.demoqa.com";
driver.Manage().Window.Maximize();
driver.FindElement(By.XPath(".//*[#id='account']/a")).Click();
driver.FindElement(By.Id("log")).SendKeys("kalyan");
driver.FindElement(By.Id("pwd")).SendKeys("kalyan");
driver.FindElement(By.Id("login")).Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>(d => d.FindElement(By.LinkText("Log out")));
Actions builder = new Actions(driver);
builder.MoveToElement(driver.FindElement(By.XPath(".//*[#id='menu-item-33']/a"))).Build().Perform();
driver.FindElement(By.XPath(".//*[#id='menu-item-37']/a")).Click();
driver.FindElement(By.ClassName("wpsc_buy_button")).Click();
driver.FindElement(By.XPath(".//*[#id='fancy_notification_content']/a[1]")).Click();
driver.FindElement(By.Name("quantity")).Clear();
driver.FindElement(By.Name("quantity")).SendKeys("10");
driver.FindElement(By.XPath("//*[#id='checkout_page_container']/div[1]/a/span")).Click();
driver.FindElement(By.ClassName("account_icon")).Click();
driver.FindElement(By.LinkText("Log out")).Click();
driver.Close();
}
}
You will need to install Microsoft Visual Studio community Edition
Create a new project as Test Project of C#
Add Selenium references from the NuGet Package Manager. Then you will be all set.
Create a new class and use [Test Class] and [Test Method] annotations to run your script
You can refer to Run Selenium C# | Setup Selenium and C# | Configure Selenium C# for more details.
Use the below code once you've added all the required C# libraries to the project in the references.
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumWithCsharp
{
class Test
{
public IWebDriver driver;
public void openGoogle()
{
// creating Browser Instance
driver = new FirefoxDriver();
//Maximizing the Browser
driver.Manage().Window.Maximize();
// Opening the URL
driver.Navigate().GoToUrl("http://google.com");
driver.FindElement(By.Id("lst-ib")).SendKeys("Hello World");
driver.FindElement(By.Name("btnG")).Click();
}
static void Main()
{
Test test = new Test();
test.openGoogle();
}
}
}

Categories

Resources