Run Chrome with a different user -Katalon and groovy - selenium-webdriver

I am using katalon and groovy for test automation.
We have a module where I need to login with different users and test the functionality.I am looking to automate the regression testing of this module but the challenge for me here is to automate the login as different user scenario, also I couldn't find any scripts that support different user login for groovy or java .
https://forum.katalon.com/t/run-chrome-with-a-different-user-than-the-one-who-started-katalon/15421/7
Please advise.
public IWebDriver CreateNewBrowserFor(string Who)
{
//Decide which of Selenium nodes we want to connect to
string CapabilitiesOfTargetUser;
if(Who.Equals("user1"))
{
//We need to control a browser for user1 on his node
CapabilitiesOfTargetUser = "platform=Mac;browserName=firefox";
}
else if(Who.Equals("me"))
{
//We need to control a browser for me on my node
CapabilitiesOfTargetUser = "platform=WINDOWS";
}
else
{
throw new ArgumentException();
}
//Create a Selenium DesiredCapabilities object that contains our choosen capabilities
Dictionary<string, object> RequestedCapabilities = new Dictionary<string, object> ();
string[] CapabilitiesArray = CapabilitiesOfTargetUser.Split(';');
foreach(string KeyValuePair in CapabilitiesArray)
{
string key = KeyValuePair.Split('=').First().Trim();
string value = KeyValuePair.Split('=').Last().Trim();
RequestedCapabilities[key] = value;
}
DesiredCapabilities Capabilities = new DesiredCapabilities(RequestedCapabilities);
//Create the RemoteWebDriver. Selenium's hub will ensure that this RemoteWebDriver is
//actually controlling a new browser on the correct machine
return new RemoteWebDriver
(
new Uri("http://localhost:4444/wd/hub")
, Capabilities
, new TimeSpan(0, 0, 50)
);
}

Related

C # + NUnit + Selenium Grid - parallel launch of several browsers on one node

Use:
C# + WebDriver+NUnit + Grid,
Implementation using Page Object+Page Factory,
WebDriver 3.4.0,
Nunit 3.5.0,
Google Chrome Driver 2.36,
Mozilla Geckodrive 0.20.0,
last updated Chrome and FF browsers
I'm trying to learn how to implement parallel test runs. Now the task is next: running one TestFixture on node in two different browsers simultaneously. I'm doing like this:
[TestFixture("chrome")]
[TestFixture("firefox")]
[Parallelizable(ParallelScope.Fixtures)]
public class LoginTests : BaseObject
{
public LoginTests(string browser)
{
DesiredCapabilities capability = new DesiredCapabilities();
capability.SetCapability("browserName", browser);
driver = new RemoteWebDriver(new Uri("http://192.168.1.63:5555/wd/hub"), capability);
driver.Navigate().GoToUrl(baseUrl);
driver.Manage().Window.Maximize();
}
private static LoginPageHelper LoginPageHelper = new LoginPageHelper();
[Test]
public static void LoginOnMailru()
{
string email = "test.account.damir#mail.ru";
string password = "q123123a";
LoginPageHelper.
DoLogin(email, password);
}
}
After performing: run 2 browsers at the same time (chrome and FF). The test passed completely in the FF browser. Chrome executed only driver.Navigate().GoToUrl(baseUrl) and an error appears
Test name: SendingMailTestForLQ.Tests.LoginTests("chrome").LoginOnMailru
Result: OpenQA.Selenium.NoSuchElementException : Could not find element by: By.Id: mailbox:submit
What I'm doing wrong, why there is an error "Could not find element by: By.Id: mailbox:submit"? Thanks!
P.S. Sorry for my English.

Fetching all Microsoft Active Directory users in Domino Xpages NamePicker via java Agent

I'm working with LDAP Microsoft Active Directory and Domino server and quite new with this.
we've successfully fetched all Microsoft Active Directory users in Domino via java Agent and have printed all the user names in java debug console. For that referred this http://lotus-blogs.blogspot.in/2009/08/ldap-programming-using-domino-java-step.html link.
Now, i want to get all users in Domino Xpages NamePicker, so is this possible to get all users in Xpages NamePicker via java Agent?
As per we see that in Xpages NamePicker, we are able to fetch the Domino Users with the help of java beans.
Any kind of suggestion will be really Appreciated.
My java Agent is like following-
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
LDAPQuery.ldapconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
}
AND
import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;
public class LDAPQuery {
public static void ldapconnect(){
String isFound="0";
try {
System.out.println("inside try 1");
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "PROVIDER_URL");
env.put(Context.SECURITY_PRINCIPAL, "UserName");
env.put(Context.SECURITY_CREDENTIALS, "password");
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Specify the ids of the attributes to return
String[] attrIDs = {"cn","mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectCategory=person)(mail=*abc.com))";
System.out.println("filter defined");
// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("", filter,ctls);
System.out.println("get the answer!");
try {
System.out.println("inside try2");
while (answer.hasMore())
{
SearchResult sr = (SearchResult)answer.next();
System.out.println("<<" + sr.getName()+">>");
Attributes attrs = sr.getAttributes();
//System.out.println(sr.getName().matches("/^[0-9]/"));
System.out.println(attrs.get("cn").get());
System.out.println(attrs.get("mail").get());
isFound="1";
}
if ( isFound=="1") {
System.out.println("User found in Active Directory!");
} else {
System.out.println("Opps ! User not found in Active Directory!");
}
answer.close();
}catch(PartialResultException e) {
System.out.println("catch 2");
e.printStackTrace();
}
// Close the context when we're done
ctx.close();
} catch (Exception e) {
System.out.println("catch 1");
e.printStackTrace();
}
}
public LDAPQuery() {
// Don't think I'm doing anything here
}
}
OK, got it.
Any particular reason why you are utilizing an Agent as opposed to using a true bean? Calling an agent everytime someone opens the name picker in my opinion is far from being effective.
Apart from that I don't see a way how the results from your agent could directly be passed into the name picker.
Third: looking at your ldap filter I'm sure that your code will return hundreds or even thousands of names. Using a standard ExtLib NamePicker is no fun for your users, believe me: the list of names displayed per dialog page is way too limited. But that may be a different story.
Sticking to the namePicker approach there are several ways how you could achieve what you appear to accomplish:
refactor your java agent into a javaBean then feed the result to the control
consider going for a directory syncing tool like IBM TDI; thus your AD data can be pushed into a Domino directory of your choice, and then from within your application you can utilize standard name lookup features

How to handle browser invocation in parallel tests using TestNG

I have been using browser invocation in #Beforeclass TestNG method using the parameter passed from testng.xml. Once the browser is invoked, I am using login test in a #BeforeMethod which is required for all the other #Tests to start. But with this setup, I am unable to run the tests in parallel. I am seeing one browser is open and login tests which is required by both tests are run in same browser and fails. All my tests are in single class file. Code structure is as below:
public class MainTest {
WebDriver driver;
BrowserFactory browser;
ReadData crmdatafile;
#BeforeClass(alwaysRun = true)
public void setup(ITestContext context) throws Exception{
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("datafile.txt").getFile());
crmdatafile = new ReadData(file.getAbsolutePath());
browser = new BrowserFactory(context.getCurrentXmlTest().getParameter("Selenium.browser"));
driver = browser.getNewBrowser();
driver.manage().deleteAllCookies();
driver.get(crmdatafile.data.get("enviornment", "url"));
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
}
#BeforeMethod()
public void login(){
System.out.println("contains the code for login which needs to be run before every test");
}
#AfterMethod
public void afterEachTest(ITestResult result) throws IOException {
driver.close();
}
#Test
public void Test1() {
System.out.println("Will run login and next steps");
}
#Test
public void Test2() {
System.out.println("Will run login and next steps");
}
public class BrowserFactory {
private WebDriver driver;
private String browser;
public BrowserFactory(String browser) {
String brow=browser.trim().toLowerCase();
if(!(brow.equals("firefox") || brow.equals("ff") || brow.equals("internetexplorer") || brow.equals("ie") || brow.equals("chrome") || brow.equals("gc"))) {
browser="ie";
}
this.browser = browser;
}
public WebDriver getNewBrowser() {
String brow = browser.trim().toLowerCase();
if(brow.equals("firefox") || brow.equals("ff")) {
System.setProperty("webdriver.gecko.driver", "drivers\\geckodriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
return driver;
}else if(brow.equals("internetexplorer") || brow.equals("ie")){
driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
return driver;
}else if(brow.equals("chrome") || brow.equals("gc")){
System.setProperty("webdriver.chrome.driver", "drivers\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
capabilities.setCapability("webdriver.chrome.binary","drivers\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
return driver;
}
return null;
}
How can I improve the above structure to run tests in parallel and using a different browser for each test?
Your test code has some issues.
You are instantiating a webdriver instance in your #BeforeClass annotated method and that is being shared by all your #Test annotated test methods. You are also invoking driver.close() in an #AfterMethod annotated method.This is a recipe for disaster because AFAIK driver.close() is equivalent to driver.quit() if you are having only one web browser instance. So what this means is that your second test method will not have a valid browser (if you are running sequentially).
If you are running in parallel, then all your test methods are going to be competing for the same browser, which is now going to cause race conditions and test failures.
You should ideally speaking move the logic of your setup() method into a listener which implements IInvokedMethodListener interface and then have this listener inject the webdriver instances into a ThreadLocal variable, which your #Test methods can then query.
You can refer to my blog post which talks in detail on how to do this.
Please check if that helps.
Here is the thing, as far as I can see you're not using annotations right and (probaly) testNG as well.
If you want to create browser instance before each test you may want to use #BeforeTest annotation. Also you may perform your test set up in this method as well. #BeforeClass annotation will be executed only once before this particular class will be executed.
It's a good idea to split tests that do different things into separate test files, case your tests do almost the same, but say params for tests are different - it's a good idea to use #DataProvider. Otherwise maybe you may want to extend your basic test with setup.
If you just want to re-execute same tests, but with different browser - consider relaunching your test job with different params or using #DataProvider as described above.
As far as I remember there are several ways to run testNG in parallel: Methods, Classes, Tests, Instances - figure out which one you need and which one works better with your setup.

How to run all cucumber functional automated test cases in single browser

I am new to cucumber testing as well as selenium testing.Please help me to run all cucumber test cases in single browser.As for now i am creating new WebDriver object in each cucumber step_def for feature file.
The solution is, Using / passing the same Web Driver object across your step_def. From your Question i assume, you have multiple Step Def files, If the stories are small and related put all of them in a single step_def file and have a single Web driver object. If it is not the case, invoke every step_def with a predefined Driver object that is globally declared in the configuration loader.
For using one browser to run all test cases use singleton design pattern i.e make class with private constructor and define class instance variable with a private access specifier.Create a method in that class and check that class is null or not and if it is null than create a new instance of class and return that instance to calling method.for example i am posting my code.
class OpenBrowserHelp {
private WebDriver driver;
private static OpenBrowserHelp browserHelp;
private OpenBrowserHelp() {
this.driver = new FirefoxDriver()
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
public static OpenBrowserHelp getOpenBrowserHelp() {
if (null == browserHelp) {
browserHelp = new OpenBrowserHelp();
}
return browserHelp;
}
WebDriver getDriver() {
return driver
}
void setDriver(WebDriver driver) {
this.driver = driver
}
public void printSingleton() {
System.out.println("Inside print Singleton");
}
Now, where ever you need to create browser instance than use
WebDriver driver = OpenBrowserHelp.getOpenBrowserHelp().getDriver();

jackrabbit start repository slow

In my current Tomcat Project, I integrated JackRabbit. Its functionality works well. However, the start of the repository is very slow. It took around 5 seconds. I think this is not bearable. Anyone has some ideas about how to integrate the Jackrabbit to the web project?
Currently, I have my own Session factory in the web project. Code is as following:
public class TMPSessionFactory {
public static Session getSession() throws RepositoryException, NamingException {
String configFile = "C:\\workspaces\\repository.xml";
String repHomeDir = "C:\\JackRabbitDemo\\repository";
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
hashTable.put(Context.INITIAL_CONTEXT_FACTORY, DummyInitialContextFactory.class.getName());
hashTable.put(Context.PROVIDER_URL, "127.0.0.1");
InitialContext ctx = new InitialContext(hashTable);
RegistryHelper.registerRepository(ctx, "repo", configFile, repHomeDir, true);
Repository r = (Repository) ctx.lookup("repo");
SimpleCredentials cred = new SimpleCredentials("admin", "admin".toCharArray());
Session session = r.login(cred, null);
return session;}}
Each time if I need a jackrabbit session, I will call this static function.
I don't know whether my way is appropriate or not since it works but not well enough (each time, the start of the repository is slow).
Do you mean you create a new repository and bind it to JNDI before doing a look up each time you want to access your repository ?
All this code:
String configFile = "C:\\workspaces\\repository.xml";
String repHomeDir = "C:\\JackRabbitDemo\\repository";
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
hashTable.put(Context.INITIAL_CONTEXT_FACTORY, DummyInitialContextFactory.class.getName());
hashTable.put(Context.PROVIDER_URL, "127.0.0.1");
InitialContext ctx = new InitialContext(hashTable);
RegistryHelper.registerRepository(ctx, "repo", configFile, repHomeDir, true);
should be only called once.
Maybe you should declared your jackrabbit repository as a Tomcat resource as it is documented here : https://jackrabbit.apache.org/shared-j2ee-resource-howto.html

Resources