Two testcases are executed in this when the first one runs but when the second runs error is thrown the same is mentioned in the image.
Why this is happening? I'm unable to solve this error.. Please help!
[TestFixture]
public class ListScenarios : ExtentManager
{
#region "Variables"
IWebDriver webDriver = new FirefoxDriver();
int rowNumber;
#endregion
[OneTimeSetUp]
public void Setup()
{
Thread.Sleep(4000);
webDriver.Manage().Window.Maximize();
webDriver.Navigate().GoToUrl("https://");
}
[Test,Order(1)]
public void AdminView()
{
rowNumber = 1;
ExcelReader.PopulateInCollection(#"TestSheet.xlsx");
test = report.CreateTest("Testcase one");
}
[Test,Order(2)]
public void ViewSlist()
{
rowNumber = 2;
ExcelReader.PopulateInCollection(#"TestSheet.xlsx");
test = report.CreateTest("Testcase two");
Thread.Sleep(2000);
if (!(webDriver.PageSource.Contains("Update")) && !(webDriver.PageSource.Contains("Unlock")))
{
test.Log(Status.Pass, "validated");
}
else
{
test.Log(Status.Fail, "Validations didnot verified");
}
}
Related
I want to start my browser only one time and then get unstatic information from there. But my browser starts many times. How can I start it only one time and close it, when my bool = false;
class Program
{
public static bool GameIsRun = true;
static void Main(string[] args)
{
CheckGame();
}
public static ChromeDriver GetDriver()
{
return new ChromeDriver();
}
public static void CheckGame()
{
while (GameIsRun)
{
GetInformation(GetDriver());
}
}
static void GetInformation(ChromeDriver driver)
{
driver.Navigate().GoToUrl("myURL");
do
{
//loop for doing something on this page, I don't want to start my browser many times.
}
while ();
}
}
May this will work for you.
class Program
{
public static bool GameIsRun = true;
public static IWebDriver driver = null;
static void Main(string[] args)
{
CheckGame();
}
public static ChromeDriver GetDriver()
{
if(driver == null){
driver = new ChromeDriver();
}
return driver;
}
public static void CheckGame()
{
while (GameIsRun)
{
GetInformation(GetDriver());
}
}
static void GetInformation(ChromeDriver driver)
{
driver.Navigate().GoToUrl("myURL");
do
{
//loop for doing something on this page, I don't want to start my browser many times.
}
while ();
}
}
For that you can use singleton concept.
public sealed class Singleton
{
private static Singleton instance=null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
Hope this will help you.
The reason behind this is while (GameIsRun) code . GameIsRun is always true that is why it goes to infinite loop.
How you can overcome this issue : you have to make the value of GameIsRun false after launching the browser just like this :
public static void CheckGame()
{
while (GameIsRun)
{
GetInformation(GetDriver());
GameIsRun = false;
}
}
Use this code , once the browser has launched , it would make GameIsRun as false.
Hope it'll help you to resolve your issue.
I need help with expanding my already build Selenium framework with WebDriver. I want to add eventHandlers that use EventFiringWebDriver on top of my code to add event for each action triggered by WebDriver for logging purposes.
To begin with, I will try to clearly present code flow.
Test starts...
Step 1. CspTestBase
public class CspTestBase : CommonElements
{
[BeforeScenario]
public void Init()
{
Initialize(); <- Code to init driver.
// more code here.
LoginPage.Goto();
LoginPage.LoginAs(TestConfig.Username).WithPassword(TestConfig.Password).Login();
}
[AfterScenario]
public void CleanUp()
{
Close();
}
When it jumps to Init method. This class holds all methods that directly require WebDriver instance.
public static class Driver
{
public static IWebDriver Instance { get; private set; }
public static void Initialize()
{
Instance = new TestDriverFactory().CreateDriver(); <- Next step
Instance.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
Instance.Manage().Cookies.DeleteAllCookies();
//Instance.Manage().Window.Maximize();
}
Then when WebDriver Instance is created:
public class TestDriverFactory
{
public IWebDriver CreateDriver()
{
return new TestBase().Create(
new LocalDriverConfig(
TestConfig.Browser));
}
}
And when it finally comes to creating actual driver:
public class TestBase
{
private static IWebDriver _driver;
//string env;
private DesiredCapabilities _capabilities;
public IWebDriver Create(LocalDriverConfig config)
{
switch (config.Browser)
{
case "Chrome":
_driver = new ChromeDriver(#"C:\Utilities");
break;
case "Firefox":
SetFirefoxCapabilities();
//_driver = new FirefoxDriver(_capabilities);
break;
...
private void SetFirefoxCapabilities()
{
...
_capabilities = DesiredCapabilities.Firefox();
//FirefoxOptions options = new FirefoxOptions();
//options.SetLoggingPreference(LogType.Browser, LogLevel.Warning);
_capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, profile);
//capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, options);
EventFiringWebDriver firingDriver = new EventFiringWebDriver(new FirefoxDriver(binary, profile, TimeSpan.FromSeconds(60)));
// copy the profile for ommiting duplicate references
firingDriver.ExceptionThrown += firingDriver_TakeScreenshotOnException;
_driver = firingDriver;
}
private void firingDriver_TakeScreenshotOnException(object sender, WebDriverExceptionEventArgs e)
{
TakeScreenshot();
}
As you can see, I'm using EventFiringWebDriver already but I want to have it done properly to save me as much work as possible.
I did some reading and looked up solutions but these were simple or in Java. Any help will be much appreciated.
I am having a lot of trouble with this. Consider this example:
public class Test {
Thread t;
public Test() {
t = new Thread(ThreadFunction);
}
public void Start() {
t.Start();
}
private void ThreadFunction() {
Thread.Sleep(5000);
Console.WriteLine("Function Complete");
}
}
public static class Main {
public Main() {
Test test = new Test();
test.Start();
// sleep longer than my worker so it finishes
Thread.Sleep(10000);
// a place to place a breakpoint
bool breakPointHere = true;
}
}
Now, I see the output of the console.log, but when I inspect Test's thread object, I see that IsAlive is still true, and ThreadStatus = TheadStatus.Running. Why is this? I wish to detect that the thread is truly complete, but I am confused as to how it can still be considered running if ThreadFunction() completes?
EDIT 2:
I finally tracked down the cause, Updating the code, and am going to answer my own question
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1 {
public abstract class Worker {
protected bool shutdown;
protected Thread t;
private bool _isStopped = true;
public bool IsStopped {
get {
return t.ThreadState == ThreadState.Stopped;
}
}
private bool _isPaused = false;
public bool IsPaused {
get {
return _isPaused;
}
}
private string stringRepresentation;
public Worker() {
t = new Thread(ThreadFunction);
stringRepresentation = "Thread id:" + t.ManagedThreadId;
t.Name = stringRepresentation;
}
public void Start() {
OnBeforeThreadStart();
t.Start();
}
public void ScheduleStop() {
shutdown = true;
}
public void SchedulePause() {
OnPauseRequest();
_isPaused = true;
}
public void Unpause() {
_isPaused = false;
}
public void ForceStop() {
t.Abort();
}
/// <summary>
/// The main thread loop.
/// </summary>
private void ThreadFunction() {
OnThreadStart();
while (!shutdown) {
if (!IsPaused) {
if (!OnLoop()) {
break;
}
}
Thread.Sleep(1000);
}
OnShutdown();
}
public abstract void OnBeforeThreadStart();
public abstract void OnThreadStart();
public abstract bool OnLoop();
public abstract void OnShutdown();
public abstract void OnPauseRequest();
public override string ToString() {
return stringRepresentation;
}
}
public class Test : Worker {
public override void OnBeforeThreadStart() {
Log.WriteLine(this + ": Thread about to be started...");
}
public override void OnThreadStart() {
Log.WriteLine(this + ": Thread Started!");
}
public override bool OnLoop() {
Log.WriteLine(this + ": I am doing the things...");
return true;
}
public override void OnShutdown() {
Log.WriteLine(this + ": Shutting down!");
}
public override void OnPauseRequest() {
}
}
public static class Log {
public delegate void LogDelegate(string text, string eventTime, Severity severity);
public static event LogDelegate OnWriteLine;
private static Queue<string> _pendingFileWrites = new Queue<string>();
public enum Severity {
Info,
Warning,
Error
}
public static void WriteLine(object line, Severity severity = Severity.Info) {
string eventTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string formatted = "[" + eventTime + "]: " + line;
Console.WriteLine(formatted);
lock (_pendingFileWrites) {
_pendingFileWrites.Enqueue(formatted);
}
if (OnWriteLine != null) {
// this is the offending line:
OnWriteLine.Invoke((string)line, eventTime, severity);
}
}
public static void WriteToFile(string path) {
lock(_pendingFileWrites) {
StreamWriter sw = File.AppendText(path);
while(_pendingFileWrites.Count > 0) {
sw.WriteLine(
_pendingFileWrites.Dequeue()
);
}
sw.Close();
}
}
}
class Program {
static void Main(string[] args) {
List<Test> tests = new List<Test>();
for(int i = 0; i < 10; i++) {
Test test = new Test();
test.Start();
tests.Add(test);
}
// sleep a little bit so they do the things
Thread.Sleep(10000);
foreach (Test test in tests) {
test.ScheduleStop();
}
bool allStopped;
do {
allStopped = true;
foreach (Test test in tests) {
if (!test.IsStopped) {
allStopped = false;
break;
}
}
} while (!allStopped);
Console.WriteLine("Done!");
// a place to place a breakpoint
bool breakPointHere = true;
}
}
}
I think your original testing that lead you to believe .IsAlive would be true had some flaw in it, I tweaked your program in your question to the following to make it compile and to be able to see which thread it created.
public class Program
{
public class Test
{
Thread t;
public Test()
{
t = new Thread(ThreadFunction);
t.Name = "TestThread";
}
public void Start()
{
t.Start();
}
private void ThreadFunction()
{
Thread.Sleep(5000);
Console.WriteLine("Function Complete");
}
}
public static void Main()
{
Test test = new Test();
test.Start();
// sleep longer than my worker so it finishes
Thread.Sleep(10000);
// a place to place a breakpoint
bool breakPointHere = true;
}
}
here is a screenshot of the running threads from inside ThreadFunction
Here is a screenshot from the end of the program
Notice that there is no "TestThread" thread.
Here is a screenshot from the locals window
IsAlive is false.
Do you really need to sleep to wait for your thread to finish?
If you don't, a better and more robust solution would be using Thread.Join()
public static class Main {
public Main() {
Test test = new Test();
test.Start();
test.Join(); // Waits for test to complete
bool breakPointHere = true;
}
}
So it turns out that my issue was that my logging method was calling a UI thread function like so:
private void LogToForm(object line, string eventTime, Log.Severity severity) {
if (dataGridView_LogInfo.InvokeRequired) {
dataGridView_LogInfo.Invoke (
new Action<object, string, Log.Severity>(LogtoFormCallback),
new object[] { line, eventTime, severity }
);
} else {
LogtoFormCallback(line, eventTime, severity);
}
}
At the Invoke() line, the thread would hang forever. The solution was to replace it with BeginInvoke() instead.
EDIT: Also, my example was/is quite poor for this. I thought I didn't understand threads at a fundamental level, and that my examples would have been enough. Hopefully someone googles this though and has this same cause, and can try this solution.
I was writing automation using C# Selenium. I wrote this code and the test keeps on failing. what do you think the problem is? chrome opens however it does not google
namespace ConsoleApplication4Sel
{
class Program
{
IWebDriver driver = new ChromeDriver();
static void Main(string[] args)
{
}
[SetUp]
public void initialization()
{
driver.Navigate().GoToUrl("http://www.google.com");
}
[Test]
public void ExcuteTest()
{
IWebElement element = driver.FindElement(By.Name("q"));
//perform ops
element.SendKeys("Execute authomation");
}
[TearDown]
public void CleanUp()
{
driver.Close();
}
}
}
Please post the error you're getting.
But in any case you forgot to link the path to the driver, meaning:
IWebDriver driver = new ChromeDriver(#"YOUR_PATH");
Put there your path, for example "D:\Download\chromedriver".
I have te code below:
[TestClass]
public class UnitTest3
{
private static FirefoxDriver _webDriver;
private TestContext testContextInstance;
private static string _baseUrl;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
public static string BaseUrl
{
get
{
return _baseUrl;
}
set
{
_baseUrl = value;
}
}
[ClassInitialize()]
public static void Initialize(TestContext testContext)
{
_webDriver = new FirefoxDriver();
}
[ClassCleanup()]
public static void Cleanup()
{
_webDriver.Quit();
}
[TestMethod]
public void OpenGoogle_PageOpenSuccessfully()
{
BaseUrl = "http://www.google.es";
_webDriver.Navigate().GoToUrl(BaseUrl);
}
}
When debugging the test _webDriver = new FirefoxDriver is left wondering and does not launch.
I'm use Selenium-Webdriver and c# unit test (mstest)
Are there any issue with firefoxdriver?
I update to Selenium Web Driver 2.33 an working successfully.
Thanks