How to change between pages with Selenium - java

I am trying to create a Test Case with Selenium, where I will create an application in one Page named "Policy". In this Application I want to create some Members. To go from Policy page to Members Page you have to press the button "Members" after you've successfully created the Policy Application. After creating all the members you need you have to navigate back to Policy page to continue.
(Main Menu Page -> Policy Page -> Members Page -> Policy Page)
I am using Page Object Pattern. I successfully log in the App, navigate to Policy Page, create the Application, but cannot go to Members Page in order to continue my Test. And of course, get back to Policy page. How can I do that? My test fails after message "Policy Created succesfully" is shown in Eclipse Console.
My code is:
#Test
public void TEST1_NavigateToPolicy() throws Exception {
MenuPage.policySelection();
}
#Test
public void TEST2_PolicyCreation() throws Exception {
PolicyPage.handleMultipleWindows("Policy");
PolicyPage.createPolicy( some requirements here);
PolicyPage.checkMessageByIdContains("Operation Apply executed Successfully", MESSAGE);
System.out.println("Policy Created succesfully");
}
#Test
public void TEST3_MemberCreation() {
//Navigate to Member Page and Create Member
PolicyPage.clickButton(MEMBERS_BUTTON);
}

Unless I'm testing the actual navigation via the UI I like to do as much navigating as possible by browsing directly to the page I need. It gives the test fewer opportunities to fail, and is often quicker as it can save extra steps.
So, I'd browse directly to the page simply using:
driver.get("yourURL");

Navigation between Policy and Members page can be done by:
#Test
public void TEST3_MemberCreation() {
// Create a policy
TEST2_PolicyCreation();
// Store the current window handle
String policyPageWindow = _webDriver.getWindowHandle();
// Clicking the "Members" button on Policy page
WebElement clickMemBerPageButton = _webDriver.findElement(By.name("MEMBERS_BUTTON"));
clickMemBerPageButton.click();
// switch focus of WebDriver to the next found window handle (that's your newly opened "Members" window)
for (String winHandle : _webDriver.getWindowHandles()) {
_webDriver.switchTo().window(winHandle);
}
//code to do something on new window (Members page)
// Switch back to policy page
_webDriver.switchTo().window(policyPageWindow);
}

Then this will be my sample code for you.
#Test
public void TEST3_MemberCreation() {
homePage = login(admin);
PolicyPage policyPage = homePage.NavigateToPolicyPage();
policyPage.handleMultipleWindows("Policy");
policyPage.createPolicy( some requirements here);
policyPage.checkMessageByIdContains("Operation Apply executed Successfully", MESSAGE);
System.out.println("Policy Created succesfully");
}
MembersPage membersPage = policyPage.clickMembersButton;(You have to handle the page navigation code inside this method and return MembersPage object)
membersPage.createMember(Data);
}
MembersPage clickMembersButton(){
element.click();
switchTo.window(newWindowHandle);
return new MembersPage();
}

Related

Google ad click is not opening the external web browser

I am trying to implement the ad in my app with Custom Native Ad Format - https://developers.google.com/ad-manager/mobile-ads-sdk/android/native/custom-formats#java_1
So, according to the documentation I am going with the approach described there and creating the ad
...
private void setListeners() {
...
imageView.setOnClickListener(v -> {
nativeCustomFormatAd.performClick("IMAGE");
});
...
}
private NativeCustomFormatAd nativeCustomFormatAd;
AdLoader adLoader = new AdLoader.Builder(context, "/6499/example/native")
.forCustomFormatAd("10063170",
new NativeCustomFormatAd.OnCustomFormatAdLoadedListener() {
#Override
public void onCustomFormatAdLoaded(NativeCustomFormatAd ad) {
// Show the custom format and record an impression.
nativeCustomFormatAd = ad;
Drawable drawable = vm.nativeCustomFormatAd.getImage("IMAGE").getDrawable();
imageView.setDrawable(drawable);
}
},
new NativeCustomFormatAd.OnCustomClickListener() {
#Override
public void onCustomClick(NativeCustomFormatAd ad, String s) {
// Handle the click action
}
})
.withAdListener( ... )
.withNativeAdOptions( ... )
.build();
#SuppressLint("VisibleForTests")
AdManagerAdRequest adManagerAdRequest = new AdManagerAdRequest.Builder().build();
adLoader.loadAd(adManagerAdRequest);
...
So, it looks pretty simple I try to make a request for the ad then I got (in a callback) NativeCustomFormatAd, save it as a class member, and along with it get drawable and set it to the imageView (to present it in the UI). Once a user clicks on the imageView I get an event in the click listener and invoke nativeCustomFormatAd.performClick("IMAGE");.
The problem is that I expect that once I transfer the ad click to the SDK (by nativeCustomFormatAd.performClick("IMAGE");) SDK is supposed to open the external browser, but instead nothing happens.
P.S. I am sure that nativeCustomFormatAd.performClick("IMAGE"); getting invoked and also I see that SDK gets the click as I got a callback event here:
...
new NativeCustomFormatAd.OnCustomClickListener() {
#Override
public void onCustomClick(NativeCustomFormatAd ad, String s) {
// Handle the click action
}
})
...
What am I missing here?
According to the docs you linked:
When a click is performed on a custom format ad, there are three possible responses from the SDK, attempted in this order:
Invoke the OnCustomClickListener from AdLoader, if one was provided.
For each of the ad's deep link URLs, attempt to locate a content resolver and start the first one that resolves.
Open a browser and navigate to the ad's traditional Destination URL.
Also:
If you pass a listener object in, the SDK instead invokes its onCustomClick method and takes no further action.
Therefore, it seems you have to pass a null OnCustomClickListener.

JAVA - Selenium WebDriver - Assertions and Waits

I am having a problem with my Assertion, or rather with the "time" the assertion is being executed. So, the assertion is working as it should, however, it is going too fast, as it is executing without waiting for the page it should be targeting to load. Which means that the assertion is failing the test.
Having this in mind, I tried searching around how to add a "wait" to the assert to make it wait for the page to load before running, but with no success.
So, would anyone, please be able to help with this, as in how would I code so, that the assert "waits" for the page to load and then executes?
I've tried adding the wait to the header method, i tried adding the wait to the test script, but no success.
public class test1 extends DriverSetup{
//Here we are setting the method to use the homePage
private HomePage homePage = new HomePage(getDriver());
//Here we are setting the method logInPage
private AuthenticationPage authenticationPage = new AuthenticationPage(getDriver());
//Here are setting the method CreateAccountPage
private CreateAccountPage createAccountPage = new CreateAccountPage(getDriver());
//Here we are setting the method to access the Website HomePage with the driver
private void accessWebsiteHomePage (){
getDriver().get("http://automationpractice.com/index.php");
}
#Test
public void CreateAccount() {
accessWebsiteHomePage();
//Log in
homePage.logInBut();
//Authentication page "Create a new account" box
authenticationPage.setCreateAccountEmailAddress(emailGenerator.Email());
authenticationPage.CreateAccountButtonClick();
Assert.assertEquals("CREATE AN ACCOUNT", createAccountPage.HeaderCheckRightPage());
The assert should be targeting the "CREATE AN ACCOUNT" page, but it is targeting the "AUTHENTICATION" page, which comes before it, hence the test fails as the "actual" value being printed is the "AUTHENTICATION" page, not the "CREATE AN ACCOUNT" page.
You need to use an explicit wait. Here is one that will wait for the title to be equal to something:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().equals(searchString);
}
You can make it more reliable by forcing the case of what you want to match like this:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
You would then need to put the following in before your assertion:
WebDriverWait wait = new WebDriverWait(driver, 10, 100);
wait.until(titleIsEqualTo("CREATE AN ACCOUNT"));
I'm making the assumption that by header you mean the page title since you haven't shown the code that collects the header.
*Edit*
A non-lambda version of the above ExpectedCondition is:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
};
}

Wicket : throw new RestartResponseException to logout and redirect

I have a problem to redirect a page after invalidating session using Wicket.
Careers1 is a page, that needs user to be logged in, with six buttons linked to other pages and an a href button, which get the user logged out.
My code apparently works, because if I click to log out, and I click to one of the six buttons, it redirects me to the log in page.
But I need it to redirect me immediately, after I clicked "log out".
I tried setResponsePage() and also adding signOut() the problem is the same of the RestartResponseException.
Here is my code
Careers1:
public class Careers1 extends WebPage
{
public Careers1()
{
Link logoutLink = new Link("logout")
{
#Override
public void onClick()
{
getSession().invalidate();
throw new RestartResponseException(Careers1.class);
}
};
add(logoutLink);
}
}
On careers.html I have
<div class="logout" > <a wicket:id="logout" href="#"> LOG OUT </a></div>
Which should invalidate the session, and redirect the user to the login.
You can try forcing wicket to redirect immediately using a fake page that just redirects back to Careers1. Let's name it RedirectorPage:
public class RedirectorPage extends WebPage
{
#Override
protected void onBeforeRender()
{
throw new RestartResponseException(Careers1.class);
}
}
Now in the logout link of Careers1 you redirect to RedirectorPage. That worked for me, but only after I moved the exception of RedirectorPage into onBeforeRender(). Throwing the exception in the page constructor still makes wicket ignore the fact the session has already been invalidated.

Wicket 6 !continueToOriginalDestination: operator ! is undefined

Situation
I'm migrating a project from Wicket 1.5.7 to Wicket 6.12, one of the errors I get is explained below.
Code
#Override
protected void onSubmit() {
final String usernameValue = mail.getModelObject();
//Password is left empty in this particular case
AuthenticatedWebSession.get().signIn(usernameValue,"");
if (!continueToOriginalDestination())
{
setResponsePage(getApplication().getHomePage());
}
}
Error
This is the error I got when changing wicket versions: The operator !
is undefined for the argument type(s) void
Note: I see this error when hovering over !continueToOriginalDestination
What did I try
In my search on stackoverflow I came accross this question:
continueToOriginalDestination does not bring me back to originating page
Also checked this topic on apache wicket:
http://apache-wicket.1842946.n4.nabble.com/Handling-ReplaceHandlerException-on-continueToOriginalDestination-in-wicket-1-5-td4101981.html#a4115437
So I changed my code to this:
#Override
public void onSubmit() {
final String usernameValue = mail.getModelObject();
AuthenticatedWebSession.get().signIn(usernameValue,"");
setResponsePage(getApplication().getHomePage());
throw new RestartResponseAtInterceptPageException(SignInPage.class);
}
Question
The old situation nor the code change seem to work in my particular case.
Maybe it's a small change, is my new code wrong, how should this work?
Has Wicket changed that much, so that the old code is not supported anymore, or can !continueToOriginalDestination be used as well?
This helps
http://www.skybert.net/java/wicket/changes-in-wicket-after-1.5/
In 1.5, you could do the following to break out of the rendering of one page, go to another page (like login page) and then send the user back to where he/she was:
public class BuyProductPage extends WebPage {
public BuyProductPage() {
User user = session.getLoggedInUser();
if (user null) {
throw new RestartResponseAtInterceptPageException(LoginPage.class);
}
}
}
and then in LoginPage.java have this to redirect the user back to BuyProductPage after he/she's logged in:
public class LoginPage extends WebPage {
public LoginPage() {
// first, login the user, then check were to send him/her:
if (!continueToOriginalDestination()) {
// redirect the user to the default page.
setResponsePage(HomePage.class);
}
}
}
The method continueToOriginalDestination has changed in Wicket 6, it's now void which makes your code look more magic and less than logic IMO:
public class LoginPage extends WebPage {
public LoginPage() {
// first, login the user, then check were to send him/her:
continueToOriginalDestination();
// Magic! If we get this far, it means that we should redirect the
// to the default page.
setResponsePage(HomePage.class);
}
}

Problem in HtmlUnit API for Java (Headless Browser)?

I am using HtmlUnit headless browser to browse this webpage (you can see the webpage to have a better understanding of the problem).
I have set the select's value to "1"
by the following commands
final WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_7);
try {
// Configuring the webClient
webClient.setJavaScriptEnabled(true);
webClient.setThrowExceptionOnScriptError(false);
webClient.setCssEnabled(true);
webClient.setUseInsecureSSL(true);
webClient.setRedirectEnabled(true);
webClient.setActiveXNative(true);
webClient.setAppletEnabled(true);
webClient.setPrintContentOnFailingStatusCode(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
// Adding listeners
webClient.addWebWindowListener(new com.gargoylesoftware.htmlunit.WebWindowListener() {
public void webWindowOpened(WebWindowEvent event) {
numberOfWebWindowOpened++;
System.out.println("Number of opened WebWindow: " + numberOfWebWindowOpened);
}
public void webWindowContentChanged(WebWindowEvent event) {
}
public void webWindowClosed(WebWindowEvent event) {
numberOfWebWindowClosed++;
System.out.println("Number of closed WebWindow: " + numberOfWebWindowClosed);
}
});
webClient.setWebConnection(new HttpWebConnection(webClient) {
public WebResponse getResponse(WebRequestSettings settings) throws IOException {
System.out.println(settings.getUrl());
return super.getResponse(settings);
}
});
CookieManager cm = new CookieManager();
webClient.setCookieManager(cm);
HtmlPage page = webClient.getPage("http://www.ticketmaster.com/event/0B004354D90759FD?artistid=1073053&majorcatid=10002&minorcatid=207");
HtmlSelect select = (HtmlSelect) page.getElementById("quantity_select");
select.setSelectedAttribute("1", true);
and then clicked on the following button
by the following commands
HtmlButtonInput button = (HtmlButtonInput) page.getElementById("find_tickets_button");
HtmlPage captchaPage = button.click();
Thread.sleep(60*1000);
System.out.println("======captcha page=======");
System.out.println(captchaPage.asXml());
but even after clicking on the button and waiting for 60 seconds through the Thread.sleep() method, I am getting the same HtmlPage.
But when I do the same thing through real browser then I get the page that contains CAPTCHA.
I think I am missing something in the htmlunit.
Q1. Why am I not getting the same page (that contains CAPTCHA) through htmlunit's browser?
The web form on that page requires the quantity_select drop-down to be filled in. You're attempting to do that in your code by assuming the drop-down is a select element. However, it's no longer a select element. Try using Firebug to inspect the drop-down and you'll see that JavaScript has replaced the select with a complex set of nested div elements.
If you figure out how to emulate each user click on the divs for that unusual drop-down then you should be able to submit the form.

Categories

Resources