Problem: LeanFT in C# doesn't have a way to open the browser in incognito mode unfortunately. I am unable to add -incognito to path as I don't have admin rights. What can I do? I was thinking Sendkeys(ā^+Nā); but not sure how to do that via keyboard or if it would work as browser is already instantiated.
Has anyone else run into this problem? It's really cumbersome like I said since LeanFT doesn't allow incognito mode to be runned automatically.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using HP.LFT.SDK;
using HP.LFT.Verifications;
using System.Diagnostics;
using System.Threading;
using HP.LFT.SDK.Web;
using HP.LFT.Report;
using System.Drawing;
namespace Xpathtest
{
[TestClass]
public class LeanFtTest : UnitTestClassBase<LeanFtTest>
{
//The Browser object on which the test will be run
IBrowser browser;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
GlobalSetup(context);
}
[TestInitialize]
public void TestInitialize()
{
browser = BrowserFactory.Launch(BrowserType.Chrome);
}
[TestMethod]
public void TestMethod1()
{
try
{
// Navigate to Rally
browser.Navigate("-incognito https://rally1.rallydev.com/");
browser.Sync();
Thread.Sleep(3000);
browser.Refresh();
// Find Username edit box using Xpath
IEditField userName = browser.Describe<IEditField>(new EditFieldDescription
{
XPath = "//input[#id='j_username']"
});
userName.SetValue("TEST");
Thread.Sleep(3000);
// Find password edit box using Xpath
IEditField password = browser.Describe<IEditField>(new EditFieldDescription
{
XPath = "//input[#id='j_password']"
});
password.SetValue("TEST");
Thread.Sleep(3000);
IButton submit = browser.Describe<IButton>(new ButtonDescription
{
XPath = "//*[#id='login-button']"
});
submit.Click();
browser.FullScreen();
Image img = browser.GetSnapshot();
Reporter.ReportEvent("Screenshot of failure", "", Status.Passed, img);
Thread.Sleep(3000);
}
catch (Exception e)
{
Assert.Fail("Unexpected Error Occurred while= " + e.Message);
}
}
[TestCleanup]
public void TestCleanup()
{
browser.Close();
}
[ClassCleanup]
public static void ClassCleanup()
{
GlobalTearDown();
}
}
}
You should use process.Start to start Chrome, and browser.Attach to a description to attach to the opened browser.
Here's the idea roughly:
using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "chrome";
process.StartInfo.Arguments = "-incognito www.somesite.com";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
BrowserFactory.Attach(new BrowserDescription
{
Url = "www.somesite.com"
});
...
But as Motti said in the comments, Attach will not work without the LeanFT extension enabled - which is disabled in incognito
Related
How Do I open google chrome using c#?
It shows System.ComponentModel.Win32Exception: 'The system cannot find the file specified'
I'd triedProcess.Start("C:\\Program Files(x86)\\Google\\Chrome\\Application\\chrome.exe"); too, but it shows the same exception
using System;
using System.Diagnostics;
namespace tempTest
{
class Program
{
static void Main(string[] args)
{
Process.Start("chrome.exe");
}
}
}
The chrome application path can be read from the registry.
You can try following codes:
var key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", false);
if(key != null)
{
var path = Path.Combine(key.GetValue("Path").ToString(), "chrome.exe");
if(File.Exists(path))
{
Process.Start(path);
}
}
I've very new to the TestStack (White) UI Automation library and I'm having a bit of an issue in terms of "hooking" the process. I'm trying to hook CCleaner, but I keep getting
An unhandled exception of type 'TestStack.White.AutomationException'
occurred in TestStack.White.dll
Additional information: Couldn't find window with title Piriform
CCleaner in process 1156, after waiting for 30 seconds:
My current code is:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using TestStack.White;
using TestStack.White.Factory;
using TestStack.White.UIItems.Finders;
using TestStack.White.InputDevices;
using TestStack.White.UIItems.WindowItems;
namespace NightWipe
{
class Program
{
private const string ExeSourceFile = #"C:\Program Files\CCleaner\CCleaner.exe";
private static TestStack.White.Application _application;
private static TestStack.White.UIItems.WindowItems.Window _mainWindow;
static void Main(string[] args)
{
clean();
}
public static string clean()
{
var psi = new ProcessStartInfo(ExeSourceFile);
_application = TestStack.White.Application.AttachOrLaunch(psi);
_mainWindow = _application.GetWindow("Piriform CCleaner");
_mainWindow.WaitWhileBusy();
return "";
}
}
}
I thought that maybe it was the name of the process since CCleaner starts another process (not CCleaner.exe) but CCleaner64.exe as seen here, which I can assume is for 64 bit operating systems maybe? Anyway I tried names including: "CCleaner", "CCleaner64"; but this threw the same exact exception.
I'm using Inspect by Microsoft and this is what it pulls for me (large image):
Inspect's information. Any idea what I'm doing wrong here?
The problem is that CCleaner is visible as WIN32 app. So GetWindow() doesn't work. You can try this code:
public void CCleanerSample()
{
var application = Application.AttachOrLaunch(new ProcessStartInfo(#"C:\Program Files\CCleaner\CCleaner.exe"));
AutomationElement ccleanerAutomationElement = null;
Console.Write("Waiting till WIN32 app is launching");
while (ccleanerAutomationElement == null)
{
ccleanerAutomationElement = AutomationElement.RootElement.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.NameProperty, "Piriform CCleaner"));
Thread.Sleep(1000);
Console.Write(".");
}
Console.WriteLine(" Done");
var mainWindow = new Win32Window(ccleanerAutomationElement, WindowFactory.Desktop, InitializeOption.NoCache,
new WindowSession(application.ApplicationSession, InitializeOption.NoCache));
}
As Above in Title
Process.Start("IExplore.exe", "http://google.com")
Does not launch IE on a VM I am using. However Executing on a server real machine and local machine it launches correctly.
Tried the following:
Process.Start("IEXPLORE.EXE", "-nomerge http://google.com/");
as suggested in post Process.Start("IEXPLORE.EXE") immediately fires the Exited event after launch.. why?
and
try
{
Process.Start("http://google.com");
}
catch (System.ComponentModel.Win32Exception)
{
Process.Start("IExplore.exe", "http://google.com");
}
and
ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
Any suggestions greatly appreciated
You got IE installed on the VM right :D? Anyway try running the app as administrator mayby the UAC settings are "wrong" on the VM.
Try this...
Process.Start("http://www.google.com");
It will launch the site with your default browser. Assuming that's Internet Explorer, you're good to go.
Here is a stripped down class that you might find useful if you want to do IE automation.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using SHDocVw;
using mshtml;
public class InternetExplorerInstance
{
public InternetExplorer Instance;
public static InternetExplorerInstance GetCurrentInternetExplorerInstance()
{
InternetExplorer currentInternetExplorer = CurrentInternetExplorer();
if ( currentInternetExplorer != null )
{
return new InternetExplorerInstance( currentInternetExplorer );
}
return null;
}
private InternetExplorerInstance( InternetExplorer ie )
{
Instance = ie;
}
public static void Iterate()
{
GetInternetExplorers();
}
private static IEnumerable<InternetExplorer> GetInternetExplorers()
{
ShellWindows shellWindows = new ShellWindowsClass();
List<InternetExplorer> allExplorers = shellWindows.Cast<InternetExplorer>().ToList();
IEnumerable<InternetExplorer> internetExplorers = allExplorers.Where( ie => Path.GetFileNameWithoutExtension( ie.FullName ).ToLower() == "iexplore" );
return internetExplorers;
}
public static void LaunchNewPage( string url )
{
InternetExplorer internetExplorer = GetInternetExplorers().FirstOrDefault();
if ( internetExplorer != null )
{
internetExplorer.Navigate2( url, 0x800 );
WindowsApi.BringWindowToFront( (IntPtr) internetExplorer.HWND );
}
else
{
internetExplorer = new InternetExplorer();
internetExplorer.Visible = true;
internetExplorer.Navigate2( url );
WindowsApi.BringWindowToFront((IntPtr) internetExplorer.HWND);
}
}
}
Not all code is included, but it should be enough for a start.
I'm researching Selenium and have a seminar for my group...
I meet many troubles with this
I use C# language and write a demo SeleniumExample.dll Then I start
selenium RC and NUnit and run it with NUnit to see the test report.
I read testdata from XML.
Here's the SeleniumExample.dll: using System;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using Selenium;
namespace SeleniumExample
{
public class Success_Login
{
//User defined
private string strURL = "http://newtours.demoaut.com/
mercurywelcome.php";
private string[] strBrowser = new string[3] { "*iehta",
"*firefox", "*safari" };
// System defined
private ISelenium selenium;
private StringBuilder verificationErrors ;
[SetUp]
public void SetupTest()
{
selenium = new DefaultSelenium("localhost", 4444,
this.strBrowser[0], this.strURL);
selenium.Start();
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
selenium.Stop();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void Success_LoginTest()
{
try
{
XmlDocument doc = new XmlDocument();
XmlNode docNode;
doc.Load("XMLFile1.xml");
docNode = doc["TestCase"];
foreach (XmlNode node in docNode)
{
selenium.Open("/");
selenium.Type("userName",
node["username"].InnerText);
selenium.Type("password",
node["password"].InnerText);
selenium.Click("login");
selenium.WaitForPageToLoad("30000");
Assert.AreEqual("Find a Flight: Mercury Tours:",
selenium.GetTitle());
}
}
catch (AssertionException e)
{
verificationErrors.Append(e.Message);
}
}
}
}
Now I want to have a demo that using Selenium Grid (SG) but I don't know
how to do. I read document and understand the way SG works. I install
SG and install Ant1.8. The tests will communicate with Selenium Hub.
Actually, I just understand the theory I don't know how to make the
tests communicate with Selenium Hub and how to make Selenium Hub
control Selenium RC.
I am a new for Selenium. If anyone know this, please help me. I
appreciate it so much.
THANKS,
Hoang
In reality there is no major difference between Selenium RC and Selenium Grid. The only difference is that with Grid you don't have to know where the RC nodes are but if you use Selenium RC you will have to.
string hubAddress = "machineNameWithSeleniumGridHub"
[SetUp]
public void SetupTest()
{
selenium = new DefaultSelenium(hubAddress, 4444,this.strBrowser[0], this.strURL);
selenium.Start();
verificationErrors = new StringBuilder();
}
When your tests run they will speak to the hub which will then push the commands out to the first available RC. I have a Selenium Tutorial on my site. It uses C# and should get you going.
Start with the simplest task of capturing the URL in Firefox from a C# application. It appears using user32.dll Windows API functions will not work as is the approach for capturing the URL within IE.
Should I need to do a capture of the URL with AutoHotkey, for example, I would send Ctrl+L (put focus in address bar and highlight content) and Ctrl+C (copy selection to clipboard). Then you just read the clipboard to get the info.
For more complex tasks, I would use Greasemonkey or iMacros extensions, perhaps triggered by similar keyboard shortcuts.
WatiN has support for Firefox.
WebAii can automate FireFox, including setting and retrieving the URL
It appears to be very beta-ey, but someone built a .net connector for mozrepl. Actually, the mozrepl codebase just moved to github. But mozrepl lets you issue commands to the Firefox's XUL environment.
Try Selenium (the Google testing engine - http://seleniumhq.org/) You can record task (Webpages UI related) done in Firefox and the convert the recording into a C# source :)
You can use Selenium WebDriver for C #.
This is a cross-platform API that allows you to control various browsers using APIs for Java, C#, among others.
Attachment of a code C # with Selenium WebDriver tests.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;
using NUnit.Framework;
using System.Text.RegularExpressions;
namespace sae_test
{ class Program
{ private static string baseURL;
private static StringBuilder verificationErrors;
static void Main(string[] args)
{ // test with firefox
IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
// test with IE
//InternetExplorerOptions options = new InternetExplorerOptions();
//options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
//IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(options);
SetupTest();
driver.Navigate().GoToUrl(baseURL + "Account/Login.aspx");
IWebElement inputTextUser = driver.FindElement(By.Id("MainContent_LoginUser_UserName"));
inputTextUser.Clear();
driver.FindElement(By.Id("MainContent_LoginUser_UserName")).Clear();
driver.FindElement(By.Id("MainContent_LoginUser_UserName")).SendKeys("usuario");
driver.FindElement(By.Id("MainContent_LoginUser_Password")).Clear();
driver.FindElement(By.Id("MainContent_LoginUser_Password")).SendKeys("123");
driver.FindElement(By.Id("MainContent_LoginUser_LoginButton")).Click();
driver.Navigate().GoToUrl(baseURL + "finanzas/consulta.aspx");
// view combo element
IWebElement comboBoxSistema = driver.FindElement(By.Id("MainContent_rcbSistema_Arrow"));
//Then click when menu option is visible
comboBoxSistema.Click();
System.Threading.Thread.Sleep(500);
// container of elements systems combo
IWebElement listaDesplegableComboSistemas = driver.FindElement(By.Id("MainContent_rcbSistema_DropDown"));
listaDesplegableComboSistemas.FindElement(By.XPath("//li[text()='BOMBEO MECANICO']")).Click();
System.Threading.Thread.Sleep(500);
IWebElement comboBoxEquipo = driver.FindElement(By.Id("MainContent_rcbEquipo_Arrow"));
//Then click when menu option is visible
comboBoxEquipo.Click();
System.Threading.Thread.Sleep(500);
// container of elements equipment combo
IWebElement listaDesplegableComboEquipos = driver.FindElement(By.Id("MainContent_rcbEquipo_DropDown"));
listaDesplegableComboEquipos.FindElement(By.XPath("//li[text()='MINI-V']")).Click();
System.Threading.Thread.Sleep(500);
driver.FindElement(By.Id("MainContent_Button1")).Click();
try
{ Assert.AreEqual("BOMBEO MECANICO_22", driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_LabelSistema\"]")).Text);
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
// verify coin format $1,234,567.89 usd
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelInversionInicial\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoOpMantto\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelcostoUnitarioEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
// verify number format 1,234,567.89
try
{ Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[#id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelConsumo\"]")).Text, "((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})?"));
}
catch (AssertionException e)
{ verificationErrors.Append(e.Message);
}
System.Console.WriteLine("errores: " + verificationErrors);
System.Threading.Thread.Sleep(20000);
driver.Quit();
}
public static void SetupTest()
{ baseURL = "http://127.0.0.1:8081/ver.rel.1.2/";
verificationErrors = new StringBuilder();
}
protected static void mouseOver(IWebDriver driver, IWebElement element)
{ Actions builder = new Actions(driver);
builder.MoveToElement(element);
builder.Perform();
}
public static void highlightElement(IWebDriver driver, IWebElement element)
{ for (int i = 0; i < 2; i++)
{ IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);",
element, "color: yellow; border: 2px solid yellow;");
js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);",
element, "");
}
}
}
}
One Microsoft tool I ran into:
UI Automation, as part of .NET 3.5
http://msdn.microsoft.com/en-us/library/aa348551.aspx
Here's an example:
http://msdn.microsoft.com/en-us/library/ms771286.aspx
I don't have UI Spy on my pc to interrogate Firefox, so I don't know if this will help out with your user32.dll problem.