Is there any way of clearing cache and free up space from android using appium python? - browser-cache

I run an app and from the app it directs me to chrome for login. After which I give my email and password and then after successful login I get redirected to app. Now the question is in case I need to run it again I need to manually clear the cache and free up space every time login happens and this does not allow me to run all codes in one stretch. Can you please let me know is there a way to automate clearing cache and free up space using python and appium.I run my code on ubuntu os platform.

Add adb shell pm clear packageName to your test file wherever you need and try

In Java, this can be achieved using AppActivity like so:
public void clearChromeStorageAndCacheAndroid() {
LogManager.debug("Resetting the Chrome app cache");
Activity clearStorage = null;
try {
clearStorage = new Activity("com.android.settings", ".applications.InstalledAppDetails");
clearStorage.setOptionalIntentArguments("package:com.android.chrome");
clearStorage.setStopApp(false);
((AndroidDriver) getDriver()).startActivity(clearStorage);
getDriverManager().setDriverTimeout(2);
boolean presentFiles = isElementDisplayed(AppiumBy.xpath("//*[#text='Files saved by websites appear here']"));
boolean presentClearAllData = isElementDisplayed(AppiumBy.xpath("//android.widget.Button[#resource-id='com.android.chrome:id/clear_button']"));
if (!presentClearAllData && !presentFiles) {
swipeUntilTextVisible("Storage", Direction.DOWN);
click(AppiumBy.xpath("//*[#resource-id='android:id/title'][starts-with(#text,'Storage')]"));
click(AppiumBy.xpath("//*[#text='Manage storage']"));
click(AppiumBy.xpath("//*[#text='MANAGE']"));
}
presentFiles = isElementDisplayed(AppiumBy.xpath("//*[#text='Files saved by websites appear here']"));
presentClearAllData = isElementDisplayed(AppiumBy.xpath("//android.widget.Button[#resource-id='com.android.chrome:id/clear_button']"));
if (presentFiles) {
} else if (presentClearAllData) {
getWait().until(ExpectedConditions.elementToBeClickable(AppiumBy.xpath("//android.widget.Button[#resource-id='com.android.chrome:id/clear_button']"))).click();
getWait().until(ExpectedConditions.elementToBeClickable(AppiumBy.xpath("//android.widget.Button[#resource-id='android:id/button1'][#text='Clear']"))).click();
presentFiles = isElementDisplayed(AppiumBy.xpath("//*[#text='Files saved by websites appear here']"));
}
((AndroidDriver) getDriver()).terminateApp("org.chromium.chrome.browser.settings");
//wait for the device to kill the app
Thread.sleep(2000);
((AndroidDriver) getDriver()).terminateApp("com.android.chrome");
Thread.sleep(2000);
((AndroidDriver) getDriver()).terminateApp("com.android.settings");
Thread.sleep(2000);
} catch (Exception ignored) {
System.out.println("ignored.getMessage() = " + ignored.getMessage());
}
}

Related

Selenium WebDriver - Chrome issue [duplicate]

This question already has an answer here:
Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium
(1 answer)
Closed 2 years ago.
Im wokring on a tool development that tests various services on Chrome browser. For each service I would need to launch a new tab on Chrome. I use the below code,
The first 2 new tabs works fine, when the 3rd tab is launched, the 1st tab's url is navigated to the one used for 3rd tab.
Not sure what's messing up. Need assistance!
I believe when your loop enters second iteration, your if statement executes to true.
You can just do following:
for(String actual: handles){
driver.switchTo().window(actual);
}
After execution of the above loop, your script will always point to last window opened.
Then you can do:
driver.get(URL + service + URL_);
outside the loop.
P.S.: If required, for more enhancement you can use below script:
private void switchToLatestBrowserWindow(WebDriver driver, Set<String> priorHandles)
{
new WebDriverWait(driver, 60).until( // keep trying to switch for 60 seconds
d -> {
Set<String> newHandles = d.getWindowHandles();
if (newHandles.size() != priorHandles.size()) {
log.Info("NewHandles Size not equal to PriorHandles size.");
String lastWindowHandle = "";
for (String windowHandle : newHandles) {
lastWindowHandle = windowHandle;
}
log.Info("LastWindowHandle Id: " + lastWindowHandle);
d.switchTo().window(lastWindowHandle);
log.Info("Switched window to " + lastWindowHandle);
return true;
} else {
return false;
}
});
}
priorHandles is set of window handles retrieved before opening new window. (the first line of code, in your case). So complete snippet would look like:
Set<String> priorHandles = driver.getWindowHandles();
((JavasriptExecutor) driver).executeScript( script: "window.open()");
switchToLatestBrowserWindow(driver, priorHandles);
driver.get(URL + service + URL_);

The element is obscured(Server did not provide stack information) automation in edge browser with selenium

org.openqa.selenium.WebDriverException: Element is obscured (WARNING: The server did not provide any stacktrace information).
This code is working fine for chrome and firefox but not with edge browser.
`public class Login {
public WebDriver driver;
By userName = By.id("ctl14_UserName");
By password = By.id("ctl14_Password");
By login = By.id("ctl14_LoginButton");
public Login(WebDriver driver) {
this.driver = driver;
}
// Set password in username textbox
public void setUserName(String strUserName) {
driver.findElement(userName).sendKeys(strUserName);
}
// Set password in password textbox
public void setPassword(String strPassword) {
driver.findElement(password).sendKeys(strPassword);
}
public void clickMyaccount(){
driver.findElement(myAccount).click();
}
// Click on login button
public void clickLogin() {
driver.findElement(login).click();
}
}
//Test class
public class AdminLogin extends BaseForDifferentLogins {
Login objLoginAdmin;
#Test(priority=0)
public void login() throws InterruptedException{
objLoginAdmin=new Login(driver);
objLoginAdmin.clickMyaccount();
Thread.sleep(3000);
objLoginAdmin.setUserName("superuser1");
objLoginAdmin.setPassword("superuser1");
Thread.sleep(3000);
objLoginAdmin.clickLogin();
Thread.sleep(3000);
}
}`
Instead of using webElement.click() you can try to build Actions with click and do perform. Had the same issue on Edge and that did the trick for me:
Actions actions = new Actions(webDriver);
actions.click(webElement).perform();
I have encountered the issue and tried several things to solve it:
enabled EdgePageLoadStrategy.Normal - did not help;
disabled the "save your password?" bubble. - did not help;
normalized the zoom level to 100% - bingo / eureka. This solved the issue.
My test script is a bit more performance-oriented, so I had no desire to add additional objects / capabilties / options. If you want your test to be more deployable add registry editing capabilities to your selenium script. This can be a starter: http://www.winhelponline.com/blog/microsoft-edge-disable-zoom-reset-zoom-level-every-start/
I encountered the same issue on the Edge browser.
It was difficult to figure out what was actually wrong, since the issue seemed to appear/disappear from time to time in my case.
So at some point I decided to contact MS and created this ticket question
Here Steven K mentioned that the obscured element error is most likely due to zoom level not being at 100% So I checked and indeed it was at 125% for some reason.
After I set it back to 100% the issue was resolved for me.
browser.send_keys [:control, '0']
I know this is a ruby+watir example, but I'm sure there is a similar Java trick for this.
I have also encountered this problem while testing Angular with Protractor in Microsoft Edge.
What finally helped me was combining two workarounds:
Set browser zoom value to 100% explicitly in beforeEach function:
browser.actions().keyDown(protractor.Key.CONTROL).sendKeys('0')
.keyUp(protractor.Key.CONTROL).perform();
Do click through browser actions:
browser.actions().mouseMove(yourElementThatIsNotActuallyObscured).click().perform();
Resetting Zoom level to 100% will fix the issue.
public void clickUntillNotObsecured(WebElement elementToClick) {
boolean obsecuredThrown = true;
int c=0;
while (obsecuredThrown && c<30) {
try {
clickOnElement(elementToClick);
obsecuredThrown = false;
} catch (WebDriverException e) {
obsecuredThrown = true;
}
c++;
}
}
You can perform the task with the Action chains in the python specially with Edge browser:
from selenium.webdriver import ActionChains
actionChains = ActionChains(driver)
button_xpath = '//xapth...'
button = driver.find_element_by_xpath(button_xpath)
actionChains.move_to_element(button).click().perform()
But sometimes Action chain does not finds the DOM element. Hence better option to use execute_script in following way which is compatible with all browsers:
button_xpath = '//xapth...'
button = driver.find_element_by_xpath(button_xpath)
driver.execute_script("arguments[0].click();", button)
Even I faced same problem today running tests on Edge, But when I observed the problem, after which step it's failing just check it up, after that step give a time delay of 5 to 10 seconds, by doing this it solved my problem. And i got the same error many times while running in Edge at different part of my program, i just added time delay at all those steps, it solved my problem and now test successfully running on EDGE.
I added delay by using
Thread.sleep(5000);
just try this, if it doesn't work for you, I found one other solution if it's failing at the time of clicking, that is perform click operation using javascript.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
This solution I got from
https://softwaretestingboard.com/qna/363/word-around-for-edge-driver-click
https://softwaretestingboard.com/qna/745/excpetion-selenium-webdriverexception-element-obscured
First one worked for me.

How to wait until page load without browser stopped respnding?

Using C# I was trying to pause execution until the page load after login so I used this code:
for (int second = 0; ; second++)
{
if (second >= 60) Assert.Fail("timeout");
try
{
if (driver.FindElement(By.Id("footer")).Displayed) break;
}
catch (Exception)
{ }
Thread.Sleep(1000);
}
But I get system error that the browser Firefox stopped responding apparently on the Thread.Sleep(1000); line so how I prevent that ?
is there another way to pause execution other than thread.sleep() ?
Edit:
I used now
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
but it execute inconstantly without waiting 10 seconds !! why ??
One soultion is using a custom WebDriverWait with an expected condition like `titleIs'. This means the driver will poll the page for a predefined amount of time waiting for the page title to match what you expect it to be. In Java it would be like so:
public Boolean waitForPageIsLoaded(String title) {
return new WebDriverWait(driver, 60).until(ExpectedConditions.titleIs(title));
}

How to handle windows download popup for IE11 using Selenium Webdriver without using AutoIT

While testing on IE11, When I click on the link to download a doc, a new blank window opens up with save and Cancel option popup. I want to hit cancel, Switch back to my current window and continue validation.
Can anyone help me how to handle this without the use of AutoIT.
If you are using selenium-webdriver with Java then you can use Sikuli-api.
Just a small introduction: Sikuli is a tool which helps to achive automation task for any software(web/standalone). Base of Sikuli is a Screenshot of the control you would like to interact with.
In your case, it is just matter of 2 buttons. Hence I would not suggest you to use seperate autoIT generated *.exe file.
Just take screenshot of OK & Cancel button.
Showing you the sample code here:
import org.sikuli.script.*;
public class Test {
Screen m_screen;
SikuliScript m_sikscr;
#Test
public void Test1() throws FindFailed
{
m_screen=new Screen();
m_screen.wait((double) 10.0);
//Click on Cancel button
m_screen.click(new Pattern("./img/CancelButton.png"));
}
}
This much should do your task.
Please Note, if at all you decide to use this method, make sure that you handle all Sikuli related dependencies in java project.
Try manually at first whether by pressing escape key it dismissing the popup.
if so follow the below code,
Robot r = null;
try {
r = new Robot();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
r.keyPress(KeyEvent.VK_ESCAPE);

Can Adobe AIR Desktop application take full screen snapshots (aka Print Screen button)

I would like to know if its possible to get full screen snapshots from an air application.
What i am interested in, is functionality similar to PrintScreen button in windows, which takes snapshots of all screens, including third party application windows, not just window in which air app is running.
If its not specific to air, and flash/flex API can provide such functionality, it also would be great.
Thanx a lot in advance.
Check out this article as it explains obtaining a screenshot by calling a native process:
import flash.filesystem.File;
import flash.events.NativeProcessExitEvent;
var process:NativeProcess;
if(NativeProcess.isSupported) {
var file:File = File.applicationDirectory;
var args:Vector.<String> = new Vector.<String>();
if (Capabilities.os.toLowerCase().indexOf("win") > -1) {
file = file.resolvePath("PATH/TO/WINDOWS/printscr");
//use your prefered screenshot tool here (e.g. https://code.google.com/p/screenshot-cmd/
//also setup the args as needed
} else if (Capabilities.os.toLowerCase().indexOf("mac") > -1) {
file = file.resolvePath("/usr/sbin/screencapture");
args[0] = "-i";
args[1] = "screencapture.png";
}
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.arguments = args;
nativeProcessStartupInfo.executable = file;
nativeProcessStartupInfo.workingDirectory = File.desktopDirectory;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(NativeProcessExitEvent.EXIT,done);
}else trace("NativeProcess NOT SUPPORTED!");
function done(e:NativeProcessExitEvent):void{
trace("screenshot comprete");
}
One important thing to bear in mind is the AIR device profile.
If you're initially testing in ADL, be sure to use the extendedDesktop profile, otherwise NativeProcess.isSupported will return false.
For more details check out the NativeProcess documentation and the Communicating with native processes in AIR developer guide