Junit capture Thread.sleep(10000); InterruptedException inside application in test? - java

I have a thread in my application that simulates working job
like this:
class FooJob {
public String work() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
}
}
I'm causing this thread to kill with a small timeout with:
executor.invokeAll(callables,2c, TimeUnit.SECONDS);
All working well
The problem is in the Junit how can I capture this InterruptedException in the test?
I don't want to add exceptions to all the program hierarchy.
The exception I'm getting:
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.blah.myapp.FooJob .work()
I guess assertThatThrownBy not going to work here as this exception not thrown
is there any way in jUnit to capture this?

Related

Wait for a thread to successfully start

I'm wondering how to log information when a server has successfully started. I cannot do this as simple as that:
createServer().start(Exit.NEVER);
System.out.println("Server is running...");
because the instruction createServer().start(Exit.NEVER) doesn't return back. This is a call to external library that uses a method with a loop similar to while(true).
I cannot also run the server in a new thread and then log information about successful start because the server may throw exception and hence there was a failure.
public void start () {
new Thread("Server") {
#Override
public void run() {
try {
createServer().start(Exit.NEVER);
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
}.start();
System.out.println("Server is running...");
}
Last solution I can think of is to wait a couple of second after createServer().start(Exit.NEVER) and then log the successful start as there was no exception thrown. This is not a perfect solution as we can wait for example 5 seconds and the log the successful start but one second later the server may throw exception.
How do I then can tell whether the server has started successfully and hence log this information?
EDIT
The server I'm using is Takes https://github.com/yegor256/takes.

Catch statements are not executed when TestNG listeners are on

I have a ITestListener to note test results. In my locator class if I try to handle something in catch statement, none of the code inside the catch is executed. For ex : I am trying to handle a WebElement that may or may not throw exception. When it throws exceptions, I should handle in the catch statement and locate different element. Since catch statement is not being executed and when the exception occurs, the applications just halts. Is there a way I could run the catch statement even when onTestFailure method is ON from TestNG ? Please suggest a solution.
//Test Script
public boolean loginVerification(String username, String password) {
try {
utilities.click(helloSignInLink, "elementToBeClickable");
reportLog("debug","info","Clicked on SignIn link");
utilities.sendText(loginID, username);
reportLog("debug","info","Username entered");
utilities.sendText(passwordID, password);
reportLog("debug","info","Password entered");
utilities.click(submit, "elementToBeClickable");
reportLog("debug","info","Clicked on submit button");
Thread.sleep(2000);
isTrue = driver.getTitle().contains("Vectors");
}
catch(Exception e) {
reportLog("debug","info","Unable to login with username : "+username+" , error message : "+e);
isTrue = false;
}
return isTrue;
}
I would recommend to catch Throwable - not just an Exception. Another thing is that when you catch something the excepttion does not really go up the stack so TestNG would never know if anything went wrong in your test and test listener would not detect failure. There is the way to push the exception further on after you have cought it. Like:
catch(Throwable e) {
reportLog("debug","info","Unable to login with username : "+username+" , error message : "+e);
isTrue = false;
throw e;
}
Can you correct your approach and let us know if the issue still exists?
P.S. - I also cannot see any assertions in your code. Assert results or Exception define the test result.
That means you are not catching the same error catch block.
Either use the same exception like TimeoutException so this block will only if TimeoutException occur. If you not sure about the error use generic exception block like Exception it will for sure going to execute if any error occur. In this case Exception will not execute for TimeoutException only because you have already specify same
try {
System.out.println("Your code");
}catch(TimeoutException t) {
System.out.println(t.getMessage());
}catch(Exception ex) {
ex.getStackTrace();
}

SAP JCO Environment method isDestinationDataProviderRegistered() fails but does not throw an exception

I have the following simple piece of code to register a DataProvider.
The line "Environment.isDestinationDataProviderRegistered()" fails. The try-catch doesn't catch it. The failure just kills the appication.
Is there a way to find out what is actually happening? There is not exception. The application just fails.
I even wrote some loggers to test the static class. All of the methods that started with Environment.in* print out the appropriate true/false response. But, when I logger out all the Environment.is* methods (also booleans), then each one kills the application.
It surprises me that a simple boolean is*() method would fail.
My code:
try {
destinationName = dbProps.getProperty(JCO_DESTINATION_NAME);
createDestination(destinationName);
if (! Environment.isDestinationDataProviderRegistered()) {
Environment.registerDestinationDataProvider(new SAPJCOUtils());
}
} catch (RuntimeException re) {
re.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

How to speed up seda shutdown?

Is there any way to stop SedaConsumer without waiting for BlockingQueue.take(pollTimeout, ...) to return? I have a lot of sedas in my application and a graceful shutdown takes a lot of time. When DefaultShutdownStrategy shutdown sedaConsumers there are no more messages in the queue and no more messages will be produced (because of implementation of routes shutdown before). So each sedaConsumer has to wait about 1 second.
Is it possible to force doStop instead of prepareShutdown for seda? Or interrupt workers threads?
I know I can decrease pollTimeout, but I afraid it will affect runtime performance.
In SedaConsumer.java:
try {
// use the end user configured poll timeout
exchange = queue.poll(pollTimeout, TimeUnit.MILLISECONDS);
// Omitted
} catch (InterruptedException e) {
LOG.debug("Sleep interrupted, are we stopping? {}", isStopping() || isStopped());
continue;
} catch (Throwable e) {
if (exchange != null) {
getExceptionHandler().handleException("Error processing exchange", exchange, e);
} else {
getExceptionHandler().handleException(e);
}
}
This construct is at most places in the thread where an InterruptedException can be thrown so if the consumer is stopping and is interrupted it will stop gracefully.

RabbitMQ Java client - How to sensibly handle exceptions and shutdowns?

Here's what I know so far (please correct me):
In the RabbitMQ Java client, operations on a channel throw IOException when there is a general network failure (malformed data from broker, authentication failures, missed heartbeats).
Operations on a channel can also throw the ShutdownSignalException unchecked exception, typically an AlreadyClosedException when we tried to perform an action on the channel/connection after it has been shut down.
The shutting down process happens in the event of "network failure, internal failure or explicit local shutdown" (e.g. via channel.close() or connection.close()). The shutdown event propagates down the "topology", from Connection -> Channel -> Consumer, and when the Channel it calls the Consumer's handleShutdown() method gets called.
A user can also add a shutdown listener which is called after the shutdown process completes.
Here is what I'm missing:
Since an IOException indicates a network failure, does it also initiate a shutdown request?
How does using auto-recovery mode affect shutdown requests? Does it cause channel operations to block while it tries to reconnect to the channel, or will the ShutdownSignalException still be thrown?
Here is how I'm handling exceptions at the moment, is this a sensible approach?
My setup is that I'm polling a QueueingConsumer and dispatching tasks to a worker pool. The rabbitmq client is encapsulated in MyRabbitMQWrapper here. When an exception occurs polling the queue I just gracefully shutdown everything and restart the client. When an exception occurs in the worker I also just log it and finish the worker.
My biggest worry (related to Question 1): Suppose an IOException occurs in the worker, then the task doesn't get acked. If the shutdown does not then occur, I now have an un-acked task that will be in limbo forever.
Pseudo-code:
class Main {
public static void main(String[] args) {
while(true) {
run();
//Easy way to restart the client, the connection has been
//closed so RabbitMQ will re-queue any un-acked tasks.
log.info("Shutdown occurred, restarting in 5 seconds");
Thread.sleep(5000);
}
}
public void run() {
MyRabbitMQWrapper rw = new MyRabbitMQWrapper("localhost");
try {
rw.connect();
while(!Thread.currentThread().isInterrupted()) {
try {
//Wait for a message on the QueueingConsumer
MyMessage t = rw.getNextMessage();
workerPool.submit(new MyTaskRunnable(rw, t));
} catch (InterruptedException | IOException | ShutdownSignalException e) {
//Handle all AMQP library exceptions by cleaning up and returning
log.warn("Shutting down", e);
workerPool.shutdown();
break;
}
}
} catch (IOException e) {
log.error("Could not connect to broker", e);
} finally {
try {
rw.close();
} catch(IOException e) {
log.info("Could not close connection");
}
}
}
}
class MyTaskRunnable implements Runnable {
....
public void run() {
doStuff();
try {
rw.ack(...);
} catch (IOException | ShutdownSignalException e) {
log.warn("Could not ack task");
}
}
}

Categories