play, java8 - re-use test fake application in tests? - testing

is there anyway to stop the actor system from shutting down and starting up between tests?
I keep getting akka exceptions complaining about the actor system being down.
I can mock/stub to get rid of the reliance on the fake app but it needs a bit of work - hoping to be able to just start one static test application up and run different things in the app.
Eg I have a (crappy) test like this - can I somehow re-use the running app between tests? it still seems to shut down somewhere along the line.
running(Fixtures.testSvr, HTMLUNIT, browser -> new JavaTestKit(system) {{
F.Promise<TestResponseObject> resultPromise = client.makeRequest("request", "parameterObject", system.dispatcher());
boolean gotUnmarshallingException = false;
try {
Await.result(resultPromise.wrapped(), TotesTestFixtures.timeout.duration());
} catch (Exception e) {
if ((e instanceof exceptions.UnmarshallingException)) {
gotUnmarshallingException = true;
}
}
if(gotUnmarshallingException == false) fail();
}});

You can try to get rid of the running method (it stops the testserver at the end) and initialize a testserver by yourself, but I don't know if Akka will be available to you:
#BeforeClass
public static void start() {
testServer = testServer(PORT, fakeApplication(inMemoryDatabase()));
testServer.start();
// Maybe you dont ned this...
try {
testbrowser = new TestBrowser(HTMLUNIT, "http://localhost:" + PORT);
} catch (Exception e) {
}
}
#Test
public void testOne() {
new JavaTestKit() {
// (...)
}
}
#AfterClass
public static void stop() {
testServer.stop();
}

Related

How to skip execution of test case from the Hooks in cucumber

I have to skip execution of the test case #bannerVerificationSMMDView only when the viewPort is Large
#Before
public void beforestartUp(Scenario scenario) throws IOException {
boolean runTest = true;
if (viewPort.contains("LARGE")) {
System.out.println("for Scenario " + scenario.getName() + " tagname are");
List<String> tags = (List<String>) scenario.getSourceTagNames();
for (String tagName : tags) {
if (tagName.contains("bannerVerificationLView"))
runTest = false;
}
try {
Assume.assumeTrue(runTest);
} catch (AssumptionViolatedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Not sure why, but exception is not getting caught
Throw a AssumptionViolatedException to skip the execution of scenario.
#Before(value="#bannerVerificationSMMDView")
public void before(Scenario scenario) {
if(viewPort.contains("LARGE"))
throw new AssumptionViolatedException("Skipping as view is LARGE");
}
If you are on cucumber version 3 plus, you can use a #BeforeStep annotation instead, keep everything else same. This will allow you to run any previous steps in the scenario and if condition is not met then skip the rest of the steps in the scenario

Plugin Development: Eclipse hangs when testing plugin

I am new to developing plugins, and was wondering what causes a test plugin to hang when started i.e. Eclipse is unresponsive.
I know that my code is working as I developed a voice recognition plugin to write to the screen what is said and when I open notepad everything I say is printed to notepad.
So I was wondering, am I missing something in the plugin life-cycle that causes the IDE to hang when my plugin is started?
package recognise.handlers;
public class SampleHandler extends AbstractHandler {
public SampleHandler() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
return null;
}
}
Does the start.startVoiceRecognition() need to be threaded?
Thanks in advance and let me know if you would like to see my manifest/activator etc.
Conclusion
Added a job separate to the UI thread
/*
* Start a new job separate to the main thread so the UI will not
* become unresponsive when the plugin has started
*/
public void runVoiceRecognitionJob() {
Job job = new Job("Voice Recognition Job") {
#Override
protected IStatus run(IProgressMonitor monitor) {
TakeInput start = new TakeInput();
try {
start.startVoiceRecognition(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// use this to open a Shell in the UI thread
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
}
As shown start.startVoiceRecognition() is running in the UI thread, and it will block the UI thread until it is finished and the app will be unresponsive during that time. So if it is doing a significant amount of work either use a Thread or use an Eclipse Job (which runs work in a background thread managed by Eclipse).
To unblock your UI you have to use Display thread.
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
MessageDialog.openInformation(shell, "Your Popup ",
"Your job has finished.");
}
});
return null;
}
You can use Display.getDefault().asyncExec() as mentioned above, so your UI will be unblocked, while your non UI code will be executing.

How to avoid Selenium runtime exception UnreachableBrowserException

I am using Selenium with GhostDriver and sometimes I got the error:
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died., caused by exceptions include java.lang.InterruptedException
It happens when using findbyElement, findByElements, get, or click methods of Selenium.
It does not happens always and not in the same places, but it happens more frequently on Windows environments.
Does anyone knows how can I avoid this exception?
I tried adding more time while using waits but it did not work.
To avoid this exception, you can override the get method. (Usually, this exception append once)
public class CustomPhantomJSDriver extends PhantomJSDriver {
#Override
public void get(String url) {
int count = 0;
int maxTries = 5;
while (count < maxTries) {
try {
super.get(url);
break;
} catch (UnreachableBrowserException e) {
count++;
}
}
if (count == maxTries) {
throw new UnreachableBrowserException(url);
}
}
}
This worked for me: http://matejtymes.blogspot.co.uk/2014/10/webdriver-fix-for-unreachablebrowserexc.html
Use it anywhere you would otherwise use PhantomJSDriver (it covers all situations: get, click, findByElement, ...)
public class FixedPhantomJSDriver extends PhantomJSDriver {
private final int retryCount = 2;
public FixedPhantomJSDriver() {
}
public FixedPhantomJSDriver(Capabilities desiredCapabilities) {
super(desiredCapabilities);
}
public FixedPhantomJSDriver(PhantomJSDriverService service, Capabilities desiredCapabilities) {
super(service, desiredCapabilities);
}
#Override
protected Response execute(String driverCommand, Map<String, ?> parameters) {
int retryAttempt = 0;
while (true) {
try {
return super.execute(driverCommand, parameters);
} catch (UnreachableBrowserException e) {
retryAttempt++;
if (retryAttempt > retryCount) {
throw e;
}
}
}
}
}

Hadoop RPC server doesn't stop

I was trying to create a simple parent child process with IPC between them using Hadoop IPC. It turns out that program executes and prints the results but it doesn't exit. Here is the code for it.
interface Protocol extends VersionedProtocol{
public static final long versionID = 1L;
IntWritable getInput();
}
public final class JavaProcess implements Protocol{
Server server;
public JavaProcess() {
String rpcAddr = "localhost";
int rpcPort = 8989;
Configuration conf = new Configuration();
try {
server = RPC.getServer(this, rpcAddr, rpcPort, conf);
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public int exec(Class klass) throws IOException,InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome +
File.separator + "bin" +
File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = klass.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(
javaBin, "-cp", classpath, className);
Process process = builder.start();
int exit_code = process.waitFor();
server.stop();
System.out.println("completed process");
return exit_code;
}
public static void main(String...args) throws IOException, InterruptedException{
int status = new JavaProcess().exec(JavaProcessChild.class);
System.out.println(status);
}
#Override
public IntWritable getInput() {
return new IntWritable(10);
}
#Override
public long getProtocolVersion(String paramString, long paramLong)
throws IOException {
return Protocol.versionID;
}
}
Here is the child process class. However I have realized that it is due to RPC.getServer() on the server side that it the culprit. Is it some known hadoop bug, or I am missing something?
public class JavaProcessChild{
public static void main(String...args){
Protocol umbilical = null;
try {
Configuration defaultConf = new Configuration();
InetSocketAddress addr = new InetSocketAddress("localhost", 8989);
umbilical = (Protocol) RPC.waitForProxy(Protocol.class, Protocol.versionID,
addr, defaultConf);
IntWritable input = umbilical.getInput();
JavaProcessChild my = new JavaProcessChild();
if(input!=null && input.equals(new IntWritable(10))){
Thread.sleep(10000);
}
else{
Thread.sleep(1000);
}
} catch (Throwable e) {
e.printStackTrace();
} finally{
if(umbilical != null){
RPC.stopProxy(umbilical);
}
}
}
}
We sorted that out via mail. But I just want to give my two cents here for the public:
So the thread that is not dying there (thus not letting the main thread finish) is the org.apache.hadoop.ipc.Server$Reader.
The reason is, that the implementation of readSelector.select(); is not interruptable. If you look closely in a debugger or threaddump, it is waiting on that call forever, even if the main thread is already cleaned up.
Two possible fixes:
make the reader thread a deamon (not so cool, because the selector
won't be cleaned up properly, but the process will end)
explicitly close the "readSelector" from outside when interrupting the threadpool
However, this is a bug in Hadoop and I have no time to look through the JIRAs. Maybe this is already fixed, in YARN the old IPC is replaced by protobuf and thrift anyways.
BTW also this is platform dependend on the implementation of the selectors, I observed these zombies on debian/windows systems, but not on redhat/solaris.
If anyone is interested in a patch for Hadoop 1.0, email me. I will sort out the JIRA bug in the near future and edit this here with more information. (Maybe this is fixed in the meanwhile anyways).

handling app that requires web service - dealing with EndpointNotFoundExceptions

I'm almost finished my first WP7 application and I'd like to publish it to the marketplace. However, one of the stipulations for a published app is that it must not crash unexpectedly during use.
My application almost completely relies on a WCF Azure Service - so I must be connected to the Internet at all times for my functions to work (communicating with a hosted database) - including login, adding/deleting/editing/searching clients and so forth.
When not connected to the internet, or when the connection drops during use, a call to the web service will cause the application to quit. How can I handle this? I figured the failure to connect to the service would be caught and I could handle the exception, but it doesn't work this way.
LoginCommand = new RelayCommand(() =>
{
ApplicationBarHelper.UpdateBindingOnFocussedControl();
MyTrainerReference.MyTrainerServiceClient service = new MyTrainerReference.MyTrainerServiceClient();
// get list of clients from web service
service.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(service_LoginCompleted);
try
{
service.LoginAsync(Email, Password);
}
**catch (Exception ex)
{
throw new Exception(ex.Message);
}**
service.CloseAsync();
});
EDIT:
My main problem is how to handle the EndpointNotFoundException in WP7 without the application crashing.
Thanks,
Gerard.
Your code should look like
LoginCommand = new RelayCommand(Login);
...
public void Login()
{
var svc = new MyTrainerReference.MyTrainerServiceClient();
try
{
svc.LoginCompleted += LoginCompleted;
svc.LoginAsync();
}
catch (Exception e)
{
svc.CloseAsync();
ShowError(e);
}
}
private void LoginCompleted(object sender, LoginCompletedEventArgs e)
{
((MyTrainerReference.MyTrainerServiceClient)sender).LoginCompleted -= LoginCompleted;
((MyTrainerReference.MyTrainerServiceClient)sender).CloseAsync();
if (e.Error == null && !e.Cancelled)
{
// TODO process e.Result
}
else if (!e.Cancelled)
{
ShowError(e.Error);
}
}
private void ShowError(Exception e)
{
// TODO show error
MessageBox.Show(e.Message, "An error occured", MessageBoxButton.OK);
}
Your code calls LoginAsync and then immediately CloseAsync, I think this will cause problems...