How to find elements in webview in android using appium - android-webview

I am new in automation testing . I am trying to find elements in webview in Android app using appium .
Below is code i am using but I am not able to find say div using its id
private AppiumDriver<WebElement> driver;
#Before
public void setUp() throws Exception {
// set up appium
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void webView() throws InterruptedException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName","Android Emulator");
capabilities.setCapability("appPackage", "com.hokucampusaffairs");
capabilities.setCapability("appActivity", "com.mybeeps.DashboardActivity");
try {
driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread.sleep(6000);
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
System.out.println(contextName);
if (contextName.contains("WEBVIEW")){
driver.context(contextName);
}
}
String pagesource= driver.getPageSource();
String url= driver.getCurrentUrl();
try {
WebElement inputField = **driver.findElement(By.id("top-container"));**
inputField.click();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Code in bold is not finding div using its id . Also findelementbyTag is only finding parent elements .
I am using latest version of appium /Android sdk/java 1.8

Exception gives you the answer - no element found with id='top-container'
Make sure you switch driver to webview
Try other locator strategies, e.g. Xpath
For webview inspection you can use chrome dev tools: https://developers.google.com/web/tools/chrome-devtools/remote-debugging/webviews

Related

org.openqa.selenium.SessionNotCreatedException on maven / appium to launch an android application

i am trying to launch an calculator app on my android device using appium on mac.
I cap all the details and then I am calling the webdriver to start the application.
But I get this error.
Image of an error
This is my class code:
public class calculator_firsttest {
public static WebDriver driver;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
openCalculator();
} catch (Exception e) {
System.out.println(e.getCause());
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void openCalculator( ) throws Exception{
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName", "Galaxy A32");
cap.setCapability("udid", "RF8RB0H517K");
cap.setCapability("platformName", "Android");
cap.setCapability("platformVersion", "11");
cap.setCapability("appPackage", "com.sec.android.app.popupcalculator");
cap.setCapability("appActivity", "com.sec.android.app.popupcalculator.Calculator");
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new RemoteWebDriver(url, cap);
System.out.println("App started.");
}
}
Thank you !

How to recognize whether is it successfully find the values for the 'asserEquals' in Selenium(POM)?

Here mentioned code successfully passed by the test run.But it was not showed the login button click and the logged-user name.(I have try to print the messages by try-catch ).but result shows as passed without those messages.
I just wanted to why can't I see the button click and assertEqual messages?
is there any coding issue or practice should be able to use to overcome this?
I have used the xml file to send the browser type.Further,I pasted only the relevant code sections.
1.TestCommands.java
public class TestCommands {
public void assertText(By locator,WebDriver driver,String expectedValue){
try {
WebElement element = driver.findElement(locator);
assertEquals(element.getText(), expectedValue);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("Not equal");
}
System.out.println("Equal");
System.out.println("captured web element: "+ locator);
System.out.println("captured expectedValue: "+ expectedValue);
}
}
2.LoginPage.java
public class LoginPage extends TestCommands{
public void loginToApplication(WebDriver driver,String userName,String password,String loggedUser){
type(userName(),driver,userName);
type(password(),driver,password);
click(loginButton(),driver);
selectByVisibleText(loggedUser(),driver,loggedUser);
}
3.TC_LoginToTest.java
public class TC_LoginToTest {
WebDriver driver ;
String baseUrl;
LoginPage login = new LoginPage();
#Parameters("browser")
#BeforeMethod
public void beforeMethod(String browser) {
if (browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "drivers\\geckodriver.exe");
driver = new FirefoxDriver();
//baseUrl = "https://test.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} else if (browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "drivers\\chromedriver.exe");
driver = new ChromeDriver();
//baseUrl = "https://test.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
}
#DataProvider
public Object[][] tc001() {
return new Object[][] {
new Object[] {"nadee","12345678","Testnadee"},
};
}
#Test(dataProvider="tc001")
public void tc001(String userName , String password ,String loggedUser) {
login.openApplication("https://test.com", driver);
login.loginToApplication(driver, userName, password, loggedUser);
}
}

How to call getPage from HtmlUnit WebClient and have setTimeout not wait forever?

I have the same problem as described in the question Call getPage from htmlunit WebClient with JavaScript disabled and setTimeout set to 10000 waits forever.
There is only one relevant (complicated) possible answer there (by theytoo). So I was wondering if:
Does someone have a simpler answer?
Can someone verify the solution works?
Code I used:
package main;
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
public class Test {
public static void main(final String[] args) {
final WebClient webClient = new WebClient();
webClient.setTimeout(1000);
try {
System.out.println("Querying");
webClient.getPage("http://www.google.com");
System.out.println("Success");
} catch (final FailingHttpStatusCodeException e) {
System.out.println("One");
e.printStackTrace();
} catch (final MalformedURLException e) {
System.out.println("Two");
e.printStackTrace();
} catch (final IOException e) {
System.out.println("Three");
e.printStackTrace();
} catch (final Exception e) {
System.out.println("Four");
e.printStackTrace();
}
System.out.println("Finished");
}
}
Output (removed all CSS and JS warnings):
Querying
Success
Finished
After changing timeout from 1000 to 1 (I won't hit google in less than 1 ms):
Querying
Three
org.apache.http.conn.ConnectTimeoutException: Connect to www.google.com:80 timed out
at com.gargoylesoftware.htmlunit.SocksSocketFactory.connectSocket(SocksSocketFactory.java:92)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:573)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:776)
at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:152)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1439)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1358)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:307)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:373)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:358)
at main.Test.main(Test.java:17)
Finished
Conclusion: I can't reproduce it and it works as expected

Google web toolkits

Can anyone please suggest a website where I can find step by step instructions on how to add jdbc to a gwt project and how to access data from a database within a gwt project? I'm new to GWT and can't to find any good resources to learn from.
Thanks
GWT is a client side technology - it creates code that runs on a browser. You can not talk to databases directly from browser. You need an intermediary servlet server. Here is what you need to do:
Use GWT-RPC for your GWT code to talk to the servlet server. There are a lot of good tutorials around the web.
Create server-side code that uses JDBC to talk to your database. Ankit already provided you with a link to example: http://code.google.com/p/gwt-examples/wiki/project_MySQLConn
You can also take a direct route and use one of the pre-packaged frameworks that allow you to talk "directly" from GWT to database, where framework provides the intermediate step (GWT-RPC to JDBC): gwtexpress
Just follow the google's tutorial itself. GWT is a java framework which converts java code into javascript code on compilation. And please dont confuse with database connection and gwt application. They are totally independent. In gwt application you will be seeing client & server packages. Only classes inside client package will be compiled to javascript code. You have to write jdbc code inside the server package. These codes will not be (can't be) compiled into javascript.
To bring the database data into client side you have to make rpc call.
I hope this information helps you for your basic understanding.
In that code you can learn how to connect database in gwt with jdbc
public class ExampleServiceImpl extends RemoteServiceServlet implements ExampleService{
//private Connection con=null;
private String status;
private String url="jdbc:mysql://localhost:3306/test";
private String user="test";
private String pass = "123456";
private Person people;
private ResultSet resultSet=null;
private Statement stm=null;
private Connection con=null;
private Statement stm2=null;
private Connection conn2=null;
private ResultSet resultSet2=null;
private MySqlConnection conn=new MySqlConnection();
#Override
public Person getPerson(String name,String surname,int password) {
Person personinfo=new Person();
personinfo.setName(name);
personinfo.setSurname(surname);
personinfo.setPassword(password);
ResultSet resultSet=null;
Statement stm=null;
Connection con=null;
MySqlConnection conn=new MySqlConnection();
con = conn.getConnection();
try {
stm = ((Connection) con).createStatement();
} catch (SQLException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
String sorgu = "SELECT * FROM person";
try {
resultSet = stm.executeQuery(sorgu);
} catch (SQLException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
while(true){
String sql = "INSERT INTO person " +
"VALUES ("+ password +", '" + name+ "','" + surname + "')";
try {
stm.executeUpdate(sql);
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
((Connection) con).setAutoCommit(false);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
((Connection) con).commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return personinfo;
}
}
public class MySqlConnection extends RemoteServiceServlet {
private static final long serialVersionUID = 1L;
public static Connection con;
public static Connection getConnection()
{
try
{
if(con==null)
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mysqlconn?user=root&password=123456";
con= DriverManager.getConnection(url);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return con;
}
public static void CloseConnection()
{
try
{
con.close();
con = null;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}

GWT client "throws Exception" cause compling problem

I try to use get result from a api called j-calais, and then out put the result on a web page, i write all the code in client, but it cant compile right, dont know why??? please help. the source code like below:
there is no obvious error arise, but it cant be compile successfully..... thanks a lot:
public void onModuleLoad() {
// Create table for stock data.
stocksFlexTable.setText(0, 0, "Type");
stocksFlexTable.setText(0, 1, "Name");
// Assemble Add Stock panel.
addPanel.add(newSymbolTextBox);
addPanel.add(addStockButton);
// Assemble Main panel.
mainPanel.add(stocksFlexTable);
mainPanel.add(addPanel);
mainPanel.add(lastUpdatedLabel);
// Associate the Main panel with the HTML host page.
RootPanel.get("stockList").add(mainPanel);
// Move cursor focus to the input box.
newSymbolTextBox.setFocus(true);
// Listen for mouse events on the Add button.
addStockButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
try {
addStock();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// Listen for keyboard events in the input box.
newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
try {
addStock();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void addStock() throws Exception {
final String url_s = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
newSymbolTextBox.setText("");
int row = stocksFlexTable.getRowCount();
CalaisClient client = new CalaisRestClient("ysw5rx69jkvdnzqf6sgjduqj");
System.out.print("read success...\n");
URL url = new URL(url_s);
CalaisResponse response = client.analyze(url);
for (CalaisObject entity : response.getEntities()) {
System.out.println(entity.getField("_type") + ":"
+ entity.getField("name"));
stocks.add(entity.getField("_type"));
stocksFlexTable.setText(row, 0, entity.getField("_type"));
stocksFlexTable.setText(row, 1, entity.getField("name"));
}
for (CalaisObject topic : response.getTopics()) {
System.out.println(topic.getField("categoryName"));
}
}
}
GWT only handles unchecked exceptions so you can throw Runtime Exceptions
or write your own Exception that extends from Runtime Exception then it will not cause any compile time problem
void f() throws NullPointerException // will not cause any problem because it is Runtime exception so unchecked
void f() throws IllegalAccessException // it is checked exception so there will be problem at compile time