Trying to write a test that checks if some words are on the page.
I'm getting a no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id='webform - submission - questionnaire - form - ajax']/section[2]"} message and the test for textIsOnThePage fails, everything else passes. Haven't used C# for a long time and trying out testing for the first time, what am I missing with textIsOnThePage ? This is the Xpath that the browser gives me.
public class Tests
{
IWebDriver driver;
String test_url = "http://mytesturl.com";
private readonly Random _random = new Random();
public void start_browser()
{
driver = new EdgeDriver(#"C:\Users\ADMIN\Downloads\edgedriver_win64");
driver.Manage().Window.Maximize();
}
//I run some tests on the page
public void test_page()
{
driver.Url = test_url;
driver.Navigate().GoToUrl("http://mytesturl.com");
Thread.Sleep(5000);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
try {IWebElement sButton2 = driver.FindElement(By.XPath("//button[#class='agree-button eu-cookie-compliance-secondary-button']"));
js.ExecuteScript("arguments[0].click()", sButton2);
} catch (Exception) { }
for (int a = 0; a < 10; a++)
{
Thread.Sleep(2500);
//I call out my method
TextIsOnThePage("weigh", "weight");
Thread.Sleep(2500);
}
private void TextIsOnThePage(string textToFind, string warning)
{
driver.Url = test_url;
driver.Navigate().GoToUrl("http://mytesturl.com");
Thread.Sleep(5000);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var element = driver.FindElement(By.XPath("//*[#id='webform - submission - questionnaire - form - ajax']/section[2]"));
if (!string.IsNullOrEmpty(element.Text) && element.Text.Contains(textToFind))
{
Console.WriteLine("Text for " + warning + "is present");
}
else
{
Console.WriteLine(warning + " test failed");
}
}
public void close_Browser()
{
driver.Quit();
}
}
Related
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Threading;
namespace TallyWhatsappsender
{
public class Class1
{
OpenQA.Selenium.IWebDriver chrome_driver = null;
public String InitProcess(String contact,String file_route,String title,String chrome_binary)
{
try
{
if (!System.IO.File.Exists(file_route))
{
return "Error : Attachment not found!";
}
if (!System.IO.File.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe")))
{
return "Error : Chromedriver.exe executable not found!\n chromedriver.exe file is missing\n update or reinstalling may fix the problem";
}
var chrome_driver_service = ChromeDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe");
chrome_driver_service.HideCommandPromptWindow = true;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Accept;
if (File.Exists(chrome_binary))
{
chromeOptions.BinaryLocation = chrome_binary;
}
chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions);
IJavaScriptExecutor javaScriptExecutor = (IJavaScriptExecutor)chrome_driver;
foreach (string ct in contact.Split(','))
{
if (string.IsNullOrEmpty(ct.Trim()))
{
break;
}
if(ct.Trim().Length != 12)
{
if (!(chrome_driver is null)) chrome_driver.Quit();
return "Error : Invalid contact number-" + ct;
}
chrome_driver.Url = "https://web.whatsapp.com/send?phone=" + ct.Trim();
try
{
chrome_driver.SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException e1)
{
Console.WriteLine(e1.Message);
}
try
{
WebDriverWait wait = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(60));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]")));
}
catch (WebDriverTimeoutException)
{
continue;
}
//sending file
IWebElement file_open = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[1]/div[2]/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_open);
chrome_driver.FindElement(By.CssSelector("input[type='file']")).SendKeys(file_route);
WebDriverWait wait2 = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(30));
wait2.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span")));
IWebElement file_send = chrome_driver.FindElement(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_send);
Thread.Sleep(1000);
//sending text
IWebElement typebox = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]"));//:chrome_driver.FindElements(By.CssSelector("div[class ='_3u328 copyable-text selectable-text']"))[0];
typebox.SendKeys(title);
IWebElement text_send = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[3]/button/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", text_send);
Thread.Sleep(3000);
}
//chrome_driver.Quit();
return "Process finished";
}
//catch (Exception ex)
//{
// if (!(chrome_driver is null)) chrome_driver.Quit();
// return ex.Message;
//}
}
}
}
I am using the above code for exporting a PDF file from tally and send it through Whatsapp Automatically.
I am facing a problem :
Every time I use this option a new tab of chrome opens and closes after sending file, because of new window it asks me to login to whatsapp every time , I think it will sort out if it do not close after sending file or when I activate it , it goes automatically to the previously opened Web.Whatsapp.com so that I will not need authentication each time.
please help me out into this .
Thanks in advance
Every time you call chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions); a new tab opens.
Try separating the initiating process and the sending process.
For example, your InitProcess method could look like the following:
public InitProcess(String chrome_binary)
{
try
{
if (!System.IO.File.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe")))
{
return "Error : Chromedriver.exe executable not found!\n chromedriver.exe file is missing\n update or reinstalling may fix the problem";
}
var chrome_driver_service = ChromeDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe");
chrome_driver_service.HideCommandPromptWindow = true;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Accept;
if (File.Exists(chrome_binary))
{
chromeOptions.BinaryLocation = chrome_binary;
}
chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions);
return "Intiated";
}
}
And then you could add a Send function:
public String Send(String contact, String file_route, String title)
{
try
{
IJavaScriptExecutor javaScriptExecutor = (IJavaScriptExecutor)chrome_driver;
foreach (string ct in contact.Split(','))
{
if (string.IsNullOrEmpty(ct.Trim()))
{
break;
}
if(ct.Trim().Length != 12)
{
if (!(chrome_driver is null)) chrome_driver.Quit();
return "Error : Invalid contact number-" + ct;
}
chrome_driver.Url = "https://web.whatsapp.com/send?phone=" + ct.Trim();
try
{
chrome_driver.SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException e1)
{
Console.WriteLine(e1.Message);
}
try
{
WebDriverWait wait = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(60));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]")));
}
catch (WebDriverTimeoutException)
{
continue;
}
//sending file
IWebElement file_open = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[1]/div[2]/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_open);
chrome_driver.FindElement(By.CssSelector("input[type='file']")).SendKeys(file_route);
WebDriverWait wait2 = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(30));
wait2.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span")));
IWebElement file_send = chrome_driver.FindElement(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_send);
Thread.Sleep(1000);
//sending text
IWebElement typebox = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]"));//:chrome_driver.FindElements(By.CssSelector("div[class ='_3u328 copyable-text selectable-text']"))[0];
typebox.SendKeys(title);
IWebElement text_send = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[3]/button/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", text_send);
Thread.Sleep(3000);
return "Process finished";
}
}
}
Now you call InitProcess only once at the beginning of you program and Send every time you want to send the file.
i am trying to add screenshot to my extent report.
I have applied exception to one of my test methods, and giving screenshot taking in exception.
Then i have called the screenshot function in teardown, so screenshot can show up in case it is failed. All good. but when i run the code that should be failing, it marks it pass due to exception, and in extent report it displays it as pass.How do i make it appear fail in extent report and display the fail screenshot with it?
namespace CreateTeamSpeed
{
class ReportsGenerationClass
{
protected ExtentReports extent;
protected ExtentTest test;
[OneTimeSetUp]
protected void Setup()
{
string path = TestContext.CurrentContext.TestDirectory + "\\";
string fileName = this.GetType().ToString() + "report.html";
var htmlReporter = new ExtentHtmlReporter(path + fileName);
extent = new ExtentReports();
extent.AttachReporter(htmlReporter);
}
[SetUp]
public void BeforeTest()
{
test = extent.CreateTest(TestContext.CurrentContext.Test.Name);
}
[TearDown]
public void AfterTest()
{
var status = TestContext.CurrentContext.Result.Outcome.Status;
var stacktrace = string.IsNullOrEmpty(TestContext.CurrentContext.Result.StackTrace) ? "" : string.Format("{0}", TestContext.CurrentContext.Result.StackTrace);
Status logstatus;
switch (status)
{
case TestStatus.Failed:
logstatus = Status.Fail;
test.AddScreenCaptureFromPath("screenshot.png");
break;
case TestStatus.Inconclusive:
logstatus = Status.Warning;
break;
case TestStatus.Skipped:
logstatus = Status.Skip;
break;
default:
logstatus = Status.Pass;
break;
}
var mediaModel = MediaEntityBuilder.CreateScreenCaptureFromPath("screenshot.png").Build();
test.Log(logstatus, "Test ended with " + logstatus + stacktrace + mediaModel);
extent.Flush();
}
[Test]
public void Test1()
{
ChromeOptions options = new ChromeOptions();
options.AddArgument("start-maximized");
IWebDriver driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("https://www.google.com");
driver.FindElement(By.Name("q")).SendKeys("Test");
driver.FindElement(By.Name("btnK")).SendKeys(Keys.Enter);
driver.Quit();
}
[Test]
public void Test2()
{
ChromeOptions options = new ChromeOptions();
options.AddArgument("start-maximized");
IWebDriver driver = new ChromeDriver(options);
try{
driver.Navigate().GoToUrl("https://www.google.com");
driver.FindElement(By.Name("qt")).SendKeys("Test");
driver.FindElement(By.Name("btnK")).SendKeys(Keys.Enter);
driver.Quit();
}
catch (Exception ex)
{
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile("screenshot.png", ScreenshotImageFormat.Png);
}
}
}
}'''
If you handle exception, it does not fail test.
To make it fail for external running tools, you can add call of Assert.Fail(); after screenshot.
I'm currently running into an issue within a loop, basically the first process works perfectly when I call -
Example of code:
public static void Search()
{
var Lines = File.ReadLines(#"in.txt").Take(1000).ToList();
var query = string.Join(Environment.NewLine, Lines);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(300));
IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("search")));
if (driver.FindElements(By.Name("search")).Count != 0)
{
driver.FindElement(By.Name("search")).SendKeys(query);
System.Threading.Thread.Sleep(2000);
driver.FindElement(By.Name("submitbtn")).Click();
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Getting Results");
if (driver.FindElements(By.CssSelector("tbody")).Count != 0)
{
Results();
}
}
}
public static void Results()
{
try
{
WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
IWebElement element1 = wait1.Until(ExpectedConditions.ElementToBeClickable(By.TagName("result")));
if (driver.FindElements(By.TagName("result")).Count != 0)
{
var element2 = driver.FindElements(By.CssSelector("text"));
foreach (var text in element2)
{
var data = text.GetAttribute("outerHTML");
System.IO.File.AppendAllText("output.txt", data + Environment.NewLine);
}
driver.Navigate().Refresh();
Search();
}
else
{
Console.WriteLine("No results");
driver.Navigate().Refresh();
Search();
}
}
catch
{
Console.WriteLine("Failed to get results");
driver.Close();
Load();
}
}
but upon returning to Search()
for a second attempt, which is called within Results
Search();
after successfully processing Results();
during the second Search process, Results() catch exception throws, ie
Failed to get results
However Results() function isn't in process :S as I called back to Search(), so my conclusion is I never exited from Results and it's still processing and after 30 seconds of not finding the element it throws an exception, but how do I call for Search() again for a second attempt & exit Results()?
I think this two lines throwing an exception:
WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
IWebElement element1 = wait1.Until(ExpectedConditions.ElementToBeClickable(By.TagName("result")));
From my perpective you don't need them since you have already:
if (driver.FindElements(By.TagName("result")).Count != 0)
If you are not sure, that results will be in DOM quickly, you can add a pause or surround also with try/catch block like this:
try {
WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
IWebElement element1 = wait1.Until(ExpectedConditions.ElementToBeClickable(By.TagName("result")));
}catch {
Console.WriteLine("No results");
}
if (driver.FindElements(By.TagName("result")).Count != 0)
PS: I'm not sure, that you need ExpectedConditions.ElementToBeClickable, since you are not clicking on the element. You can use ExpectedConditions.ElementToBeVisible for example.
I keep getting a StaleElementReferenceException error when I try to find all links and navigate through them in my console application, I have the following code and tried all day to fix it yesterday but with no result:
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting the browser...");
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.site.ro");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Gathering the Links...");
List<IWebElement> links = new List<IWebElement>();
try
{
foreach (IWebElement item in driver.FindElements(By.TagName("a")))
{
try
{
if (item.Displayed == true)
{
item.Click();
Console.WriteLine("Item is displayed \a\n" + "Navigating to link...");
} else
{
continue;
}
Random r1 = new Random();
Random r2 = new Random();
Random r3 = new Random();
var last = r3.Next(1, 10) * 700;
var mseconds = r2.Next(1, 10) * 500;
var time = mseconds + r1.Next(1, 10) * 300;
Console.WriteLine("Waiting for " + (time + last) + " miliseconds before next link");
System.Threading.Thread.Sleep(time + last);
driver.Navigate().Back();
System.Threading.Thread.Sleep(2000);
}
catch (Exception e2)
{
Console.WriteLine(e2);
Console.ReadLine();
}
}
}
catch (Exception e1)
{
Console.WriteLine(e1);
Console.ReadLine();
}
Console.WriteLine("Test finished.");
driver.Quit();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
}
driver.FindElements(By.TagName("a")) is finding for you all the links on the page.
Then you are going to the another page using the first link : item.Click();
Finally you are going back driver.Navigate().Back();
But that's not the initial page (by selenium's opinion). And all the links stored at the first step are gone because your initial page is gone. That's why you can't click the second of them.
You need to refind all the links after each driver.Navigate().Back();
Or better store all the hrefs to a list like linksList.Add(Item.getAttribute("href")); and use stored hrefs.
I have a table containing details about jobs.
Currently I can use the following code to find the specified job and select delete.
[TestMethod]
public void DeleteJob()
{
JobsPage.GoTo();
JobsPage.Delete("TestJobTitle");
Assert.IsTrue(DeleteJobPage.IsAt, "Delete job page not displayed");
}
Below Method to find the specified job and click delete
public static void Delete(string delete)
{
var test = Driver.Instance.FindElement((By.XPath("//table/tbody/tr[td[2] = '" + delete + "']/td[9]/a[3]")));
test.Click();
}
I am now attempting to find a way to confirm the Job is no longer displayed on the JobsPage.
Assert.IsTrue(JobsPage._View("TestJobTitle"), "Job is still present");
The above Assert in the TestMethod is not working
I attempted the below method but need help to get working.
public static bool _View(string view)
{
IList<IWebElement> messages = Driver.Instance.FindElements(By.XPath("//table/tbody/tr[td[2] = '" + view + "']")).ToList();
foreach (IWebElement message in messages)
{
if (message.Text == view)
{
return true; // Job is still present
}
}
return false; // Job is not present
}
Don't know whether this helps or not. I have same scenario and I do search in a table for a user still exists or not.
public static bool ValidateSearchResult(string s)
{
bool val = false;
try
{
new WebDriverWait(Drivers._driverInstance, new TimeSpan(0, 0, 10)).Until(ExpectedConditions.ElementExists(By.TagName("tbody")));
IList<IWebElement> StatusColumnData = Drivers._driverInstance.FindElements(By.XPath("//table/tbody/tr/td[2]"));
foreach (IWebElement element in StatusColumnData)
{
if (element.Text.Contains(s))
{
val = true;
break;
}
else
val = false;
return val;
}
}
catch(Exception e)
{
throw (e);
}
}