PHPUnit Selenium2 driver. closeWindow() - phpunit

Can somebody explain to me why the testcase having closeWindow() function in the middle is failing with the communication to the server error, and another one doesn't:
FAILED:
public function test1()
{
$this->url('http://www.yahoo.com');
$this->closeWindow();
$this->url('http://www.google.com');
}
PASSED:
public function test1()
{
$this->url('http://www.yahoo.com');
$this->url('http://www.google.com');
}
closeWindow() is not suppose to clear the session unlike close(), right?

Related

Correct way to fail a unit test from within a callback using Vertx Unit

Given the following unit test, which uses the Vertx Unit testing framework:
#RunWith(VertxUnitRunner.class)
public class VertxUnitTest {
private Vertx vertx;
#Rule
public RunTestOnContext rule = new RunTestOnContext(new VertxOptions().setClustered(false)
.setClusterManager(new HazelcastClusterManager()).setMaxEventLoopExecuteTime(2000000000000L)
.setMaxWorkerExecuteTime(60000000000000L).setBlockedThreadCheckInterval(1000000)
.setEventBusOptions(new EventBusOptions().setClustered(false).setIdleTimeout(0)));
#Before
public void setup() throws Exception {
io.vertx.core.Vertx v = rule.vertx();
vertx = Vertx.newInstance(v);
}
private class MyVerticle extends AbstractVerticle {}
#Test
public void runFlow_correctMessage_stepsCalledInCorrectOrder(TestContext context) {
Async async = context.async();
vertx.getDelegate().deployVerticle(new MyVerticle(), new DeploymentOptions().setWorker(true), c -> {
c.cause();
vertx.eventBus().<Object>send("", new JsonObject(), new DeliveryOptions(), rpl -> {
async.complete();
fail();
});
});
}
}
the call to fail() is throwing an exception to the console, but it is not actually failing the test itself, which finishes successfully and is green.
The same is true when working with Mockito. I can successfully verify the behavior of the verticle and its dependencies using mocks, but even when the Mockito assertions fail, the test itself will still pass. Calling fail on the vertx TestContext object - context.fail() - will also not fail the test.
The core issue is this: any call to fail() after async.complete() will not fail the test, only the console will show the error. But without the call to async.complete(), the code in the verticle (called upon consuming from the event bus), will not have run before the test assertions are called.
Without the call to async.complete(), the test will it appears never complete.
What is the correct approach to this?
Thanks
the correct approach is to call the TestContext.fail() method, like so:
#Test
public void runFlow_correctMessage_stepsCalledInCorrectOrder(TestContext context) {
Async async = context.async();
vertx.getDelegate().deployVerticle(new MyVerticle(), new DeploymentOptions().setWorker(true), c -> {
if(c.succeeded()) {
vertx.eventBus().<Object>send("", new JsonObject(), new DeliveryOptions(), rpl -> {
if(rpl.succeeded()) {
// make assertions based on reply contents, and then...
async.complete();
} else {
context.fail(rpl.cause());
}
});
} else {
context.fail(c.cause());
}
});
}

Why is my RestEasy WebService blocked when my #Asynchronous method is working?

I am trying to run heavy tasks asynchronously. The client then polls the server to know when the job is done. This seemed to work, but I noticed that my WebService that responds to the polling is blocked when I put a breakpoint in my #Asynchronous Method.
This is what I did:
JobWS.java // Used to start a job
#RequestScoped
#Path("/job")
#Produces(MediaType.APPLICATION_JSON)
public class JobWS {
#POST
#Path("/run/create")
public Response startJob(MyDTO dto) {
return ResponseUtil.ok(jobService.createJob(dto));
}
}
JobService.java // Creates the job in the DB, starts it and returns its ID
#Stateless
public class JobService {
#Inject
private AsyncJobService asyncJobService;
#Inject
private Worker worker;
public AsyncJob createJob(MyDTO dto) {
AsyncJob asyncJob = asyncJobService.create();
worker.doWork(asyncJob.getId(), dto);
return asyncJob; // With this, the client can poll the job with its ID
}
}
Worker.java // Working hard
#Stateless
public class Worker {
#Asynchronous
public void doWork(UUID asyncJobId, MyDTO dto) {
// Do work
// ...
// Eventually update the AsyncJob and mark it as finished
}
}
Finally, my Polling Webservice, which is the one being blocked
#RequestScoped
#Path("/polling")
#Produces(MediaType.APPLICATION_JSON)
public class PollingWS {
#Inject
AsyncJobService asyncJobService;
#GET
#Path("/{id}")
public Response loadAsyncJob(#PathParam("id") #NotNull UUID id) {
return ResponseUtil.ok(asyncJobService.loadAsyncJob(id));
}
}
If I put a breakpoint somwhere in doWork(), the PollingWS does not respond to HTTP requests anymore. When I debug through doWork(), occasionally I get a response, but only when jumping from one breakpoint to another, never when waiting at a breakpoint.
What am I missing here ? Why is my doWork() method blocking my Webservice, despite it running asynchronously ?
I found the culprit. A breakpoint suspends all threads by default. In IntelliJ, a right click on it will open the following dialog:
When changing the "Suspend" property to "Thread", my WS is not blocked anymore and everything works as expected. In retrospect, I feel a bit stupid for asking this. But hey... maybe it will help others :)

Is it possible to run a Retrofit observable synchronously?

I'm trying to migrate my app to work with RxJava.
I already use Retrofit and therefore I'm trying to use a Retrofit interface which methods return Observables.
However I'm now having issues with coding tests against it, as I can't get the Observable to run on the main thread; I'm trying to use Scheduler.immediate() for it.
It seems that Retrofit doesn't allow to override it's behaviour, which makes totally sense for the real execution flow, but it makes testing very difficult.
As I've just started with RxJava + Retrofit I just hope I'm doing something wrong instead.
Below is what the code looks like:
#Test
public void shouldCompleteRequest() {
SomeRestRequest request = new SomeRestRequest(arg1, arg2);
TestSubscriber<SomeRestResponse> testSubscriber = new TestSubscriber<>();
new SomeRestCommand(mRestApi,
arg1, arg2
Schedulers.immediate(),
Schedulers.immediate(),
mMockEventBus).execute(request, testSubscriber);
testSubscriber.assertCompleted();
}
where
public void execute(T request, Observer<S> observer) {
getCommand(request)
.observeOn(mObserveOnScheduler) //The test injects Schedulers.immediate()
.subscribeOn(mSubscribeOnScheduler) //The test injects Schedulers.immediate()
.subscribe(observer);
}
,
#Override
protected Observable<SomeRestResponse> getCommand(SomeRestRequest request) {
return mRestApi.restCommand(arg1, arg2);
}
and
public interface RestApi {
#GET("/someEndPoint")
Observable<SomeRestResponse> restCommand(#Query("arg1") String arg1, #Query("arg2") String arg2);
}
If you modify your test to add testSubscriber.awaitTerminalEvent();, then your test will wait for the call to complete and hence the test will pass. You will still have to do an assertCompleted() as the terminal event can be either of successful completion or error.
#Test
public void shouldCompleteRequest() {
SomeRestRequest request = new SomeRestRequest(arg1, arg2);
TestSubscriber<SomeRestResponse> testSubscriber = new TestSubscriber<>();
new SomeRestCommand(mRestApi,
arg1, arg2
Schedulers.immediate(),
Schedulers.immediate(),
mMockEventBus).execute(request, testSubscriber);
testSubscriber.awaitTerminalEvent(); // add this line here
testSubscriber.assertCompleted();
}
I looked up the source code of Retrofit 1.9.0 and as per RxSupport class, the call is always executed in a separate thread provided by the httpExecutor. Hence using Schedulers.immediate() did not cause the call to happen in the main thread.

Http communication with C application

I have a C program and that runs a web server. I have a Air Application and I want to communicate with that web server using Air Application. I create a socket object and do the following.
public function httpTest():void
{
sock.addEventListener(Event.CONNECT, onConnect);
sock.addEventListener(ProgressEvent.SOCKET_DATA, onDataRecv);
sock.addEventListener(IOErrorEvent.IO_ERROR, onError);
try
{
trace("Connecting...");
sock.connect("127.0.0.1", 9800);
sock.writeMultiByte("GET /Connection?data=version", "us-ascii");
sock.flush();
}
catch(err:Error)
{
trace(err.message);
}
}
public function onConnect(event:Event):void
{
trace("onConnect +");
}
public function onDataRecv(event:ProgressEvent):void
{
trace("onDataRecv +");
}
public function onError(event:Event):void
{
trace("onError +");
}
socket connects successfully and its connection event is fired. but when I try to request the connection url nothing is received on server side. am I missing something. Thanks
Like just about everything to do with networking in Flex, socket.connect is asynchronous and non-blocking, meaning that just because sock.connect has returned without error it doesn't mean the socket is actually ready for use yet. I suspect that if you put trace(sock.connected) in your original code after your call to writeMultiByte it will print false.
You will need to delay your sock.writeMultiByte call until the connection is ready, which isn't until your onConnect handler fires. Try:
try
{
trace("Connecting...");
sock.connect("127.0.0.1", 9800);
}
catch(err:Error)
{
trace(err.message);
}
...
public function onConnect(event:Event):void
{
trace("onConnect +");
sock.writeMultiByte("GET /Connection?data=version", "us-ascii");
sock.flush();
}
I made a mistake. I did not add HTTP version and string terminator in the Get String. Thats why I did not receive any print on server side. Because the request was invalid. I posted the working code. Thanks for help.
public function httpTest():void
{
sock.addEventListener(Event.CONNECT, onConnect);
sock.addEventListener(ProgressEvent.SOCKET_DATA, onDataRecv);
sock.addEventListener(IOErrorEvent.IO_ERROR, onError);
try
{
trace("Connecting...");
sock.connect("127.0.0.1", 9800);
sock.writeMultiByte("GET /Connection?data=version HTTP/1.0\r\n\r\n", "us-ascii");
sock.flush();
}
catch(err:Error)
{
trace(err.message);
}
}
public function onConnect(event:Event):void
{
trace("onConnect +");
}
public function onDataRecv(event:ProgressEvent):void
{
trace("onDataRecv +");
}
public function onError(event:Event):void
{
trace("onError +");
}

How to handle wait during a datadriven test using testNG in a webdriver script

This is my scenario, i use webdriver with testNG for doing data driven test. I am observing that the data i am 'seeing' in web app which is provided by #dataprovider is missing some value. For exg if i have an array as {"1","2","3","4","5"}, i am getting these value in webdriver script using testNG #dataprovider, i am observing in the 'Web GUI' initially 2 might be displayed, then in the next iteration 5 is displayed then the test stop.
I am assuming that TestNG is not waiting for webdriver to complete the function or process.
Here is my sample code
#Test (dataProviderClass=MyDataProviders.class)
public class MyWebDriverClass{
#Test(dataProvider = "theProviderName")
public void providerHomeCreateuser(String arg1,String arg2)
{
<..input arg1, arg2 to text fields..>
}
}
I understand somewhere i need to put a Thread.wait(), could any body guide me on this.
Data provider method is as follows
public class MyDataProviders {
...
...
#DataProvider (name="theProviderName")
public static Object[][] getData() throws Exception
{
Object retObject[][]=getTableArray("src\\com\\abcd\\resource\\TestData.xls", 5, "MyTestData");
return retObject;
}

Resources