Clear cookies before starting new test using SafariDriver - java

Does anyone know how to clear the cache on a new start of a test while running SafariDriver? I've tried to use java robot to keypress command + option + e, but that does not seem to work. It does not focus on the browser.
Robot r = new Robot();
try {
Robot robot = new Robot();
r.keyPress(KeyEvent.META_MASK);
r.keyPress(KeyEvent.VK_META);
r.keyPress(KeyEvent.VK_E);
r.keyRelease(KeyEvent.VK_E);
r.keyRelease(KeyEvent.VK_META);
r.keyRelease(KeyEvent.META_MASK);
} catch (AWTException e) {
e.printStackTrace();
}
Ive also tried to do an actions.builder method but that does not seem to work
String clearCache = Keys.chord(Keys.CONTROL, Keys.COMMAND, "E");
Actions builder = new Actions(browser);
builder.sendKeys(clearCache);
Action clearCacheAction = builder.build();
clearCacheAction.perform();
I've also looked into using SafariDriver options but my java is not that good to fully understand how to implement it. Below is the code that Ive been trying to use. I created a SafariOptions Class and tried to instantiate it in my #before class.
package test
import org.openqa.selenium.safari.SafariDriver;
public class SafariOptions extends SafariDriver {
private static SafariOptions ourInstance = new SafariOptions();
public static SafariOptions getInstance() {
return ourInstance;
}
public void setUseCleanSession(boolean useCleanSession){
}
public SafariOptions() {
boolean useCleanSession = true;
}
}
#Before
public void createDriver() {
assumeTrue(isSupportedPlatform());
browser = new SafariDriver();
SafariDriver options = new SafariOptions();
}
Nothing seems to clear the Safari cache on each test run.

Quick and easy solution for all who might want to know.
Add the following code to a .sh file to root.
killall cookied
rm -rf ~/Library/Caches/com.apple.Safari/*
rm -rf ~/Library/Safari/LocalStorage/*
rm -rf ~/Library/Cookies/*
Call on the file in #Before
Runtime runtime = Runtime.getRuntime();
runtime.exec("file.sh");
System.out.println("Cookies Removed");

Related

How do I call a #Before method from my Hooks class, in TestRunner?

I am setting up an automated framework to run tests on Android emulators, using Appium. I have added logic to launch Appium and the emulator programatically, but would like to be able to edit the "launch settings" from the TestRunner class.
My ideal goal is to have everything I need in the TestRunner class, so I can run my tests against a specific port, emulator, and tags.
But currently with the method I have now, I am receiving the following error:
'Message: cucumber.runtime.CucumberException: Hooks must declare 0 or 1 arguments.'
#CucumberOptions(
plugin = {"pretty", "html:target/cucumber-reports"}
, monochrome = true
, features = "src/test/java/feature"
, tags = "#Login"
)
public class TestRunner {
public void run() throws MalformedURLException, InterruptedException {
setUpDriver(4723, "Android9");
}
}
_________________________________________________________
public class Hooks extends DriverFactory {
static AppiumDriverLocalService service;
#Before
public static void setUpDriver(int port, String simulator) throws InterruptedException {
service = AppiumDriverLocalService
.buildService(new AppiumServiceBuilder().usingPort(port)
.usingDriverExecutable(new File("path/to/node/file"))
.withAppiumJS(new File("/path/to/appium/file")));
System.out.println("\n Appium server: " + service.getUrl());
service.start();
Thread.sleep(2000);
try {
setUpMobileDriver(simulator);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
You can pass from Maven or you can use System properties

Why is my selenium webdriver opening blank windows of "data;"

I'm trying to set up my webdriver so that it can execute tests in parallel from the xml sheet, this it does, but I find sometimes it opens up blank chrome windows of "data;"
I've researched around other questions and all the answers seem to say things about putting the webdriver as a new threadlocal<RemoteWebDriver>, which I am already doing.
This is the WebDriverSetup.java file I am using:
public class WebDriverSetup {
private static ThreadLocal<RemoteWebDriver> threadDriver = null;
public WebDriver driver(){
return threadDriver.get();
}
#BeforeMethod
public void setUp() throws MalformedURLException {
//Set up the path to the chromedriver so that the user will not have problems if they don't have the system path variable set up.
System.setProperty("webdriver.chrome.driver", TestExecutor.projectDirectory + "/chromedriver.exe");
//Set the hub URL
String seleniumUrl = "http://" + TestExecutor.hubUrl + "/wd/hub";
//Turn off logging because as of selenium-standalone-server-3.0.1, there
//is an "INFO" message that appears in console that could be mistaken for
//an error message.
Logger.getLogger("org.openqa.selenium.remote").setLevel(Level.OFF);
//threadDriver needs to be on its own local thread
threadDriver = new ThreadLocal<RemoteWebDriver>();
//Set chromeoptions so they open headless on the VM, but the VM imagines the
//tests as if chrome was running full screen on a desktop session.
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--window-size=1920,1080");
//Apply the options to the chromedriver session.
URL seleniumHubURL = new URL(seleniumUrl);
threadDriver.set(new RemoteWebDriver(seleniumHubURL, options));
}
}
and this is how I am calling it from my test:
public class Demo_1_Filter_Users_By_Firstname extends TestBase.ClassGlobals
{
private WebDriverSetup webDriverSetup;
private EventFiringWebDriver driver;
private File logFile;
#Test
public void main(){
//The main method
driver.get("web_application_url");
}
#BeforeMethod
public void testSetup() throws IOException {
//Setup the webdriver
webDriverSetup = new WebDriverSetup();
driver = new EventFiringWebDriver( webDriverSetup.driver() );
//Set up an eventhandler on the event so that all the logging functions work
EventHandler handler = new EventHandler();
driver.register( handler );
//Setup the logfile
logFile = commonMethods.newLogFile();
//Log
commonMethods.log(logFile, "------TEST STARTED------");
}
#AfterMethod
public void testClosure(){
//Close webdriver session, log test done etc
}
}
The error that I am experiencing doesn't happen every time, and I don't understand why the window is hanging on data; even though the first line of my main method is to create a new webdriver session, and then using that session, open the web application through driver.get()
I am using chromedriver version 2.41
The latest stable version of ChromeDriver (88.0.4324.96) appears to have fixed this:
Resolved issue 3641: Page not getting loaded/rendered when browser window is not in focus with Chrome Beta v87 and chromedriver v(87/86)
I've been having this issue for a while and updating my chromedriver.exe file finally solved it.

Run the appium server programmatically

I am trying to run the Appium server programmatically. I tried all the possible options that Appium is providing, but not getting any result
From the command line, if I am trying C:\Users\User>appium it's starting the server. How to do the same by using java code?
Note: the version of Appium is 1.6.5
AppiumDriverLocalService service=AppiumDriverLocalService.buildDefaultService();
service.start();
This the code what i am using to run the appium server programmatically .
The error i am getting is
java.lang.NoClassDefFoundError: org/apache/commons/validator/routines/InetAddressValidator
Did you tried this,
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec("appium");
}
}
I know you are asking for Java, but I do this programmatically with C#. So I paste my solution in case it can help to get an idea:
C# Code:
public void startAppiumServerLocally()
{
try
{
string nodejs = "\"" + Environment.GetEnvironmentVariable("nodejs") + "\""; // Environment path for node.exe
string appium = "\"" + Environment.GetEnvironmentVariable("appium") + "\""; // Environment path for main.js or appium.js
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(nodejs);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.RedirectStandardError = true;
myProcessStartInfo.CreateNoWindow = true;
// getOverride() method returns '--session-override'
// getDesiredCapabilitiesJson() returns a JSON with some capabilities '--default-capabilities {"udid":identifier..., deviceName: "Samsung S7"....}'
// getDriverPort() returns --port X just in case I need to start in a different and unused port.
string args = appium + getOverride() + getDesiredCapabilitiesJson() + getDriverPort();
myProcessStartInfo.Arguments = args;
nodeProcess = new Process();
nodeProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
nodeProcess.StartInfo = myProcessStartInfo;
nodeProcess.Start();
nodeProcess.BeginErrorReadLine();
StreamReader myStreamReader = nodeProcess.StandardOutput;
while (_bAppiumForceEnd == false)
{
if (_bAppiumInit == false)
{
string line = myStreamReader.ReadLine();
if (line.Contains("listener started"))
{
// _bAppiumInit is a flag to start my tests once the server started
_bAppiumInit = true;
}
}
else
{
myStreamReader.ReadLine();
}
}
myStreamReader.Close();
}
catch (Exception e)
{
//Log(e.Message);
}
}
I know that creating a while loop is not the best solution, but sometimes my nodeProcess was not stoping... So I changed it to this way, and it works perfectly.
Make sure you installed Appium globally...
npm install -g appium
Here is how you start and stop appium server programmatically using Java code
import java.nio.file.Paths;
public class AppiumSetupAndTearDown {
public static void startAppiumServer() throws IOException, InterruptedException {
String logDir = <the path where you want to create the appium output file>;
File appiumOutput = new File(logDir);
if (!appiumOutput.exists()) {
boolean status = appiumOutput.createNewFile();
if (!status) {
throw new IOException("Failed to create Appium output file!");
}
}
String cmd[] = {"/bin/bash", Paths.get(System.getProperty("user.dir")).getParent().getParent().toString() + "/Modules/Shared/startAppium.sh"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectError(new File(logDir));
pb.redirectInput(new File(logDir));
pb.redirectOutput(new File(logDir));
pb.start();
System.out.println("Appium server started!");
}
public static void stopAppiumServer() throws IOException, InterruptedException {
String cmd[] = {"/bin/bash", Paths.get(System.getProperty("user.dir")).getParent().getParent().toString() + "/Modules/Shared/stopAppium.sh"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.start();
System.out.println("Appium server stopped!");
}
}
You can also add Thread.sleep(5000) after starting and stopping the appium server in case you run into timing issues.
Try to addthe commons validator lib to your classpath/pom.xml (commons-validator-1.4.0.jar)

How would I make my methods loop through an enum?

I have an Environment enum and an Application enum. Each application also has its own class which has a test for that app. I want to run each test in all the environments before it goes on to the next test. Here is part of what I have in the main method
for(Environment env :Environment.values())
{
new AccountInventory(env);
AccountInventory.accountInventoryTests(null, env);
new AuditActionItems( env);
AuditActionItems.auditActionItemTests(null, env);
new SalesPipeline(env);
SalesPipeline.salesPipelineTests(null, env);
Here is an example of what I have in a class
public static boolean accountInventoryTests(Application app, Environment env)
{
WebDriver driver = new InternetExplorerDriver();
try{
driver.get(env.getDomain() + Application.ACCOUNTINVENTORY.getContextRoot());
driver.findElement(By.name("j_username")).sendKeys(USER);
driver.findElement(By.name("j_password")).sendKeys(PASSWORD);
driver.findElement(By.cssSelector("input[type='submit']")).click();
Right now it runs all the tests in one environment, then runs all of them in the next environment. Thanks in advance.
Your code looks like that you doesn't need to iterate your application-enum for your test, because you access them in your test-methods(see Application.ACCOUNTINVENTORY.getContextRoot()).
If you realy want to iterate your enum, you can try mabye this:
for(Environment env :Environment.values())
{
new AccountInventory(env);
for(Application app: Application.values())
{
AccountInventory.accountInventoryTests(app, env);
}
new AuditActionItems( env);
for(Application app: Application.values())
{
AuditActionItems.auditActionItemTests(app, env);
}
...
}
Hope it helps

JADE_mulli agent system

I can't deploy the agent in JADE implemented in Java, any alternatives ?
package package1;
import jade.core.Agent;
public class JadePFE extends Agent {
#Override
protected void setup() {
System.out.println("Hello agent 007");
}
}
I think you mean to start the JADE platform, this is the contents of the my main method which launches the whole thing. Hope it helps
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] args1 = new String[3];
args1[0] = "-gui";
args1[1] = "-agents";
args1[2] = "agentName:package.agentClassName";
jade.Boot.main(args1);
}
}
If I have understand, you want know how deploy an agent (and maybe start the platform) directly from the code.
I show you how:
import jade.core.Runtime;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.*;
public class Start {
public static void main(String args[]) throws InterruptedException, StaleProxyException {
// Get a hold on JADE runtime
Runtime runTime = Runtime.instance();
// Exit the JVM when there are no more containers around
runTime.setCloseVM(true);
// Create a profile and the main container and start RMA
Profile mainProfile = new ProfileImpl(true);
AgentContainer mainContainer = runTime.createMainContainer(mainProfile);
AgentController rma = mainContainer.createNewAgent("rma", "jade.tools.rma.rma", null);
rma.start();
Thread.sleep(500);
// Create a Sniffer
AgentController sniffer = mainContainer.createNewAgent(
"mySniffer", "jade.tools.sniffer.Sniffer",
new Object[]{"BuyerAgent1;BuyerAgent2;ShipperAgent1;ShipperAgent2"});
sniffer.start();
Thread.sleep(500);
// Create a Introspector
AgentController introspector = mainContainer.createNewAgent(
"myIntrospector", "jade.tools.introspector.Introspector",
null);
introspector.start();
Thread.sleep(500);
// Prepare for create and fire new agents:
Profile anotherProfile;
AgentContainer anotherContainer;
AgentController agent;
/* Create a new profile and a new non-main container, connecting to the
default main container (i.e. on this host, port 1099)
NB. Two containers CAN'T share the same Profile object: create a new one. */
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a BuyerAgent...");
agent = anotherContainer.createNewAgent("BuyerAgent1", "transfersimulation.BuyerAgent", new Object[0]);
agent.start();
Thread.sleep(900);
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a BuyerAgent...");
agent = anotherContainer.createNewAgent("BuyerAgent2", "transfersimulation.BuyerAgent", new Object[0]);
agent.start();
Thread.sleep(900);
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a ShipperAgent...");
agent = anotherContainer.createNewAgent("ShipperAgent1", "transfersimulation.ShipperAgent", new Object[0]);
agent.start();
Thread.sleep(900);
return;
}
}
This works if no other JADE Platform is already running.

Categories

Resources