Writing selenium errors to a log file and handling errors - java

I have a selenium script and I need to write the failures to a log file. For example if a page is not found or selenium.waitForPageToLoad expires. Instead of going straight to tearDown(), I would like to log why my script has stopped.
selenium.open("/confluence/login.action?logout=true");
selenium.type("os_username", "login");
selenium.type("os_password", "pw");
selenium.click("loginButton");
selenium.waitForPageToLoad("10000");
selenium.click("title-heading");
selenium.click("spacelink-INTR");
selenium.waitForPageToLoad("10000");
selenium.click("link=Create Issue Links");
selenium.waitForPageToLoad("10000");
selenium.click("quick-search-query");
selenium.type("quick-search-query", "create issue links");
selenium.click("quick-search-submit");
selenium.waitForPageToLoad("100000");
stoptime = System.currentTimeMillis();
Also would it be possible to skip a steap if it fails, right now if anything at all fails it will go straight to the teardown() method.
I am using java.

What you are asking is exception handling. If any of the steps in your tests fails then selenium will throw an exception and tests would stop. If you handle the exceptions using try catch then you should be able to achieve what you are looking for. As an example, see the code below. This would handle the initial page load timeout. Even if selenium.open fails, script will handle the exception and move ahead to next statement. You should read more about exception handling to find what is the best way to handle these exceptions.
try{
selenium.open("/confluence/login.action?logout=true");
}
catch(Exception e)
{
//Code to write data to a file goes here
System.out.println("Selenium open did not work")
}

Related

picocli exception behavior changed?

I'm in the process of updating from picocli 3.9.6 to 4.2.0, and I'm running into an issue when replacing old deprecated calls with the new versions.
In my original version, I had a code block like this:
try {
return commandLine.parseWithHandlers(
new RunLast().useOut(ps),
new ExceptionHandler(),
args);
}
catch(Exception e) {
// handle exceptions
}
The ExceptionHandler handles both parameter and execution exceptions -- both are rethrown, but parameter exceptions get the help text added to the exception text. The catch would get hit in cases where, e.g., a command was given bad args. The catch would ensure the error was printed in the UI.
I attempted to update it like this:
try {
commandLine.setOut(pw);
ExceptionHandler handler = new ExceptionHandler();
commandLine.setExecutionExceptionHandler(handler);
commandLine.setParameterExceptionHandler(handler);
commandLine.execute(args);
return commandLine.getExecutionResult();
}
catch(Exception e) {
// handle exceptions
}
With this new version, exceptions are thrown as before, but they are no longer caught by the catch block after being rethrown by the ExceptionHandler. How can I catch these exceptions?
One of the changes in picocli 4.x is the new execution framework. The user manual has a section on migration that may be useful.
By design, the CommandLine::execute method never throws an exception. So there is no need to surround the call to CommandLine::execute with a try/catch block (unless you need to catch an Error or Throwable).
Instead, you can optionally specify custom exception handlers, like you already do in your example. These exception handlers is where you can show an error message to the users. (Perhaps a combination of what was in the previous ExceptionHandler and the logic that previously was in the catch block.)
The ParameterExceptionHandler is invoked when the user provided invalid input. The default handler shows an error message, may suggest alternative spellings for options or subcommands that look like a typo, and finally displays the usage help message. The Handling Errors section of the user manual has an example ShortErrorMessageHandler that may be useful when the usage help message is so long that it obscures the error message.
The ExecutionExceptionHandler is invoked when the business logic throws an exception. The default handler just rethrows the exception, which results in a stack trace being printed. The Business Logic Exceptions section of the user manual shows an alternative.
It sounds like you need a custom ExecutionExceptionHandler that prints a stack trace followed by the usage help message.

logging issue while using jdbc

I'm using jdbc for the first time and reading from a file which contains sql queries I wrote earlier. Although the queries are properly executed and my program goes on without any apparent issue, After I've statement.executeBatch();, I cannot write anything into my log anymore.
-I'm using the java.util.logging to do my logging with a FileHandler. To read my ".sql" file, I'm using a BufferedReader and a FileReader. I know I'm not sharing a lot of code to fully understand the context, but that's all I have from memory. I'm closing all the readers after use.
Any ideas what could be the problem?
MyLogger.log(Level.WARNING, "it does write");
statement.executeBatch();
MyLogger.log(Level.WARNING, "it doesn't write anymore");
statement.close();
MyLogger.log(Level.WARNING, "still doesn't");
Thanks
edit: MyLogger is a class with a statig log method
edit2: #Tim Biegeleisen
statement.executeBatch() returns an array of int, one for each batch. I tried :
try {
int[] results = statement.executeBatch();
for (int result : results)
{
if (result == Statement.EXECUTE_FAILED)
{
MyLogger.log(Level.SEVERE, "batch failed, but driver seems to still be alive.");
System.out.println("batch failed, but driver seems to still be alive.");
}
}
} catch (SQLException e) {
MyLogger.log(Level.SEVERE, "the batch failed, and the driver died too.");
System.out.println("the batch failed, and the driver died too.");
}
and it printed and logged nothing.
edit3: I guess I was asking too much of my shutdown hook. I'm not familiar with it so I'm not sure what was precisely the problem.
The explanation which seems most likely to me is that your code is rolling over upon hitting executeBatch(). After this, the subsequent calls to the logger do not appear to be working, because they aren't being hit at all. One simple way to test this would be to surround your call to executeBatch() with a try catch block:
try {
int result = statement.executeBatch();
if (result == Statement.EXECUTE_FAILED) {
MyLogger.log(Level.ERROR, "batch failed, but driver seems to still be alive.");
}
} catch (SQLException e) {
MyLogger.log(Level.ERROR, "the batch failed, and the driver died too.");
}
I guess I was asking too much of my shutdown hook. I'm not familiar with it >so I'm not sure what was precisely the problem.
See: LogManager$Cleaner() can prevent logging in other shutdown hooks.
If you are trying to perform logging in a shutdown hook then you are racing with the LogManager$Cleaner thread.
As a workaround to creating a custom shutdown hook you can create a custom handler and install it on the root logger.
The first action of the LogManager$Cleaner is to close all the installed handlers on the logger.
Once the cleaner calls the close on the custom handler you can then do one of the following:
Have LogManager$Cleaner run your shutdown code inside the handler.
Find your custom shutdown hook using the Thread API and join with it which will block the cleaner thread.

Selenium RemoteWebDriver - Do something if element could not be found

I am trying to develop a Suite of classes for testing my websites functionality every night and I do this in Chrome, Firefox, Edge and IE. Because sometimes Selenium doesn't find an element I need something that e.g. takes a screenshot of the browser before giving out an error. I don't need a function for taking a screenshot I need something that triggers when Selenium can't continue.
Best regards,
MK
If I understand correct, you need to set up the trigger for your another system, which can react on Selenium test error.
In your test code you can use :
try {
// find element and test code
} catch (NoSuchElementException e) {
// set up the trigger code
}
To notify another system you can choose any system, which can provide notification mechanism.
In your case, you could use for example Redis with pub/sub.
So your reaction system will be a subscriber and test - provider of the event.

Getting unreachable statement error even though it reaches during run time in spring hibernate

I am trying to catch exceptions which will occur during run time in spring hibernate below is hibernate code which inserts data into sql table but i want to catch certain exceptions but i am getting below
error:
Unreachable catch block for JDBCConnectionException.
This exception is never thrown from the try statement body
try
{
TokenBo tokenBo = (TokenBo)appContext.getBean("TokenBo");
Token token = new Token();
token.setFirstName(FirstName);
tokenBo.save(token);
}
catch(JDBCConnectionException e1) {}
Runtime Exception & Error are supposed to happen at run time (reporting that something went wrong when the program ran) and ConstraintViolationException is a runtime exception
The error you are getting is because ConstraintViolationException is never thrown from your code.
Why would you even want to catch ConstraintViolationException? This exception states that you failed to fulfill one of the DB constraints, which means you didn't have proper data check in place
To avoid "chat" mode in commens:
The error message is pretty self-explanatory:
This exception is never thrown from the try statement body
Remove the catch block for the ConstraintViolationException. Don't try to handle Exceptions that can not be thrown by your code.
If you remove this, and running your code causes a JDBCConnectionException, you'll need to tackle this problem, not creating another one to hide it.
If you need help to fix that issue, you'll have to provide more code/configuration/stacktrace/...

RuntimeException does not halt GAE but returns HTTP 500 when run locally

Let me first provide some background information. If you don't care you can skip to the next paragraph. I wanted to use the DrEdit sample Java application which is integrated with Google Drive as the basis of my application. I need to refactor the code, though, because the original scenario assumed that the user would only access the application through the Drive and never directly. Currently when the latter happens, a RuntimeException is thrown which should not be the case in a normal flow.
Thanks to that issue I stumbled upon a difference between my local environment and the GAE which is manifested when the following code is run:
} catch (CredentialMediator.NoRefreshTokenException e) {
try {
resp.sendRedirect(e.getAuthorizationUrl());
} catch (IOException ioe) {
throw new RuntimeException("Failed to redirect user for authorization");
}
throw new RuntimeException("No refresh token found. Re-authorizing.");
}
When I run this application on GAE, the RuntimeException is thrown (I can see it in the logs) and the sendRedirect is also executed so I get to see the page that should be displayed.
However when I run the same application locally, I get the HTTP 500 error and the RuntimeException is displayed but the sendRedirect is ignored.
So far I haven't been successful in finding an explanation for this behaviour. I would like to know why this is the case and if there are settings that I can change in order to fully replicate the GAE environment locally.
This is how standard defines the sendRedirect(). It actually commits the response so after calling this method you should not be able to change or add to the response. However it does not define what happens if you trigger an exception after redirect.
Anyway, your code is ambiguous on purpose - you should not continue processing the request and throw exceptions after sending redirect. If you have any processing to do, then do it before redirect.
OTOH you should not rely on generic exception handling. Instead install a servlet filter that catches exceptions and return a proper user-readable or device-readable response.

Categories