On Sep 21, 2016, at 6:33 AM, Psycho Punch <rdg...@gmail.com> wrote:
I'm new to Vert.x and I'm trying to figure out how to do unit tests for event bus handlers. Most of the documentation I see regarding testing have examples using HTTP components for testing. However, I'm working on a very simple handler for events using the event bus, and I'm not really sure how to set up the tests for it.
I'm not sure what the community's general view of StackOverflow is, but I've posted a question about my problem in there earlier. Please check it out for more details. If you'd rather I repost the question in here, please let me know.
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+un...@googlegroups.com.
Visit this group at https://groups.google.com/group/vertx.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/bfc3a8b0-e648-49ef-9c76-a88537bfadb1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
@Rule
public final RunTestOnContext vertxRule = new RunTestOnContext();
@Before
public void setUp(TestContext context) {
vertx = vertxRule.vertx();
//verticle is set up with mock delegate before deployment
vertx.deployVerticle(verticle);
}
@After
public void tearDown(TestContext context) {
vertx.close(context.asyncAssertSuccess());
}
@Test
public void testDelegate(TestContext context) {
EventBus eventBus = vertx.eventBus();
Event event = new Event("id", "description")
eventBus.publish("event.channel", Json.encode(event));
//Mockito.verify
verify(delegate).invokeMethod(anyString(), anyString());
}
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+un...@googlegroups.com.
Visit this group at https://groups.google.com/group/vertx.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/9ef227db-09e5-491f-8f7a-e80ae2003fbd%40googlegroups.com.
On Sep 21, 2016, at 8:29 AM, Psycho Punch <rdg...@gmail.com> wrote:
That was what I had in my test code originally, but my problem with that was that the code doesn't seem to leave the @Before (setUp) method. It just hangs in there seeming to wait for anything...
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+un...@googlegroups.com.
Visit this group at https://groups.google.com/group/vertx.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/e40d0b10-9dc1-4509-8b5a-863f1e6fb597%40googlegroups.com.
private Delegate delegate;
@Override
public void start(Future<Void> future) throws Exception {
vertx.eventBus().consumer("event.channel", message -> {
logger.info("received!");
Event event = Json.decodeValue(message.body().toString(), Event.class);
delegate.invokeMethod(event.getId(), event.getDescription());
});
}
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+un...@googlegroups.com.
Visit this group at https://groups.google.com/group/vertx.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/14dd58bc-6471-4a61-983b-50ccd1561d80%40googlegroups.com.
you can call complete() at the end of the method after the consumer registration or you can call it in the consumer completion (MessageConsumer#completionHandler(ar) method) handler if you want to wait that the message consumer registration is propagated accross the cluster
On Sep 21, 2016, at 8:39 AM, Psycho Punch <rdg...@gmail.com> wrote:
I have the following code in my Verticle. I'm just defining a handler for the event bus in here, and I'm not really sure where to call future.complete(). Originally, I had it after the definition of the handler, but it didn't seem to make any change; deployment still stalls...
private Delegate delegate;
@Override public void start(Future<Void> future) throws Exception { vertx.eventBus().consumer("event.channel", message -> { logger.info("received!"); Event event = Json.decodeValue(message.body().toString(), Event.class); delegate.invokeMethod(event.getId(), event.getDescription()); }); }
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+unsubscribe@googlegroups.com.
Visit this group at https://groups.google.com/group/vertx.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/14dd58bc-6471-4a61-983b-50ccd1561d80%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+unsubscribe@googlegroups.com.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/C4A20C6E-E86F-4369-8544-29C9CCE87BCE%40julienviet.com.
private Delegate delegate;
@Override
public void start(Future<Void> future) throws Exception {
vertx.eventBus().consumer("event.channel", message -> {
logger.info("received!");
Event event = Json.decodeValue(message.body().toString(), Event.class);
delegate.invokeMethod(event.getId(), event.getDescription());
}).completionHandler(result -> {
if (result.succeeded()) {
future.complete();
} else {
future.fail(result.cause());
}
});
}
java.lang.IllegalStateException: Result is already complete: succeeded
at io.vertx.core.impl.FutureImpl.checkComplete(FutureImpl.java:164) ~[vertx-core-3.3.3.jar:na]
at io.vertx.core.impl.FutureImpl.complete(FutureImpl.java:108) ~[vertx-core-3.3.3.jar:na]
at io.vertx.core.impl.FutureImpl.handle(FutureImpl.java:135) ~[vertx-core-3.3.3.jar:na]
at io.vertx.core.impl.FutureImpl.handle(FutureImpl.java:23) ~[vertx-core-3.3.3.jar:na]
at io.vertx.core.eventbus.impl.EventBusImpl.lambda$callCompletionHandlerAsync$2(EventBusImpl.java:340) ~[vertx-core-3.3.3.jar:na]
at io.vertx.core.impl.ContextImpl.lambda$wrapTask$2(ContextImpl.java:316) ~[vertx-core-3.3.3.jar:na]
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) ~[netty-common-4.1.5.Final.jar:4.1.5.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:418) ~[netty-common-4.1.5.Final.jar:4.1.5.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:440) ~[netty-transport-4.1.5.Final.jar:4.1.5.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:873) ~[netty-common-4.1.5.Final.jar:4.1.5.Final]
at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_102]
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+unsubscribe@googlegroups.com.
Visit this group at https://groups.google.com/group/vertx.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/233ac1cd-c4d7-460d-b098-d4e98dfb2165%40googlegroups.com.
Thomas,
Yeah, I saw the conversation on the issue over at GitHub. Any guesses as to why my test is still failing?
--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+unsubscribe@googlegroups.com.
Visit this group at https://groups.google.com/group/vertx.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/f86ca807-4b54-4710-b05c-5ede9eaac74c%40googlegroups.com.
@Test
public void testDelegate(TestContext context) {
final Async async = context.async();
doAnswer(args -> {
async.complete();
return null;
}).when(delegate).invokeMethod(anyString(), anyString());
EventBus eventBus = vertx.eventBus();
Event event = new Event("id", "description")
eventBus.publish("event.channel", Json.encode(event));
//Mockito.verify
async.awaitSuccess();
verify(delegate).invokeMethod(anyString(), anyString());
}
I wonder though if there is a better way to do this...--
You received this message because you are subscribed to the Google Groups "vert.x" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vertx+unsubscribe@googlegroups.com.
Visit this group at https://groups.google.com/group/vertx.
To view this discussion on the web, visit https://groups.google.com/d/msgid/vertx/9c4725ee-f87c-4df8-b2c8-dcddb301f8a0%40googlegroups.com.
import io.vertx.core.logging.Logger
import io.vertx.core.logging.LoggerFactory
import io.vertx.groovy.core.Vertx
import io.vertx.groovy.core.http.HttpServer
import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.AsyncConditions
import static groovy.json.JsonOutput.prettyPrint
import static groovy.json.JsonOutput.toJson
/**
* Test the Authenticator Verticle
*/
class AuthenticatorSpec extends Specification {
@Shared Logger LOG
@Shared def GOOD_TOKEN = 'GOODTESTTOKEN'
@Shared def BAD_TOKEN = 'BADTESTTOKEN'
@Shared HttpServer server
@Shared def userSuccess = '''{
"type": "cc.v3.user.user",
"self": "https://user.mycompany.com/v3/user/deven.phillips%40mycompany.com",
"name": {
"given": "Deven",
"family": "Phillips"
},
"email": "deven.p...@mycompany.com",
"settings": {},
"roles": {
"read": true,
"modify": true,
"create": false,
"delete": false,
"admin": false,
"replication.source": true
}
}'''
@Shared Vertx vertx
def setupSpec() {
System.setProperty('vertx.logger-delegate-factory-class-name', 'io.vertx.core.logging.Log4j2LogDelegateFactory')
vertx = Vertx.vertx()
LOG = LoggerFactory.getLogger(AuthenticatorSpec)
def config = [
userServiceHost: 'localhost',
userServicePort: 1024 + ((int)(Math.random() * 1000)),
userServiceSSL: false
]
def deployment = [config: config]
vertx.exceptionHandler({ e ->
LOG.error("Unhandled exception", e)
})
def conditions = new AsyncConditions(2)
LOG.info('Deploying Authenticator verticle')
vertx.deployVerticle('groovy:com.mycompany.cc.indexer.workers.Authenticator', deployment) { res1 ->
conditions.evaluate {
def status = res1.succeeded()
LOG.debug("Verticle Status: ${status}")
assert status
}
}
LOG.info('Create Mock user service')
server = vertx.createHttpServer().requestHandler({ req ->
def headers = prettyPrint(toJson(req.headers()))
LOG.info("HEADERS: ${headers}")
def authHeader = req.headers().get('Authorization')
if (authHeader && authHeader =~ /^Bearer .*$/) {
LOG.debug(authHeader)
def token = authHeader.replaceAll(/^Bearer /, '')
LOG.debug("TOKEN: ${authHeader}")
if (token == GOOD_TOKEN) {
req.response().putHeader('Content-Type', 'application/json').end(userSuccess)
} else if (token == BAD_TOKEN) {
req.response().setStatusCode(404).setStatusMessage('NOT FOUND').end()
} else {
req.response().setStatusCode(400).setStatusMessage('BAD REQUEST').end()
}
}
}).listen(config.userServicePort, '0.0.0.0') { res2 ->
conditions.evaluate {
def status = res2.succeeded()
LOG.debug("HTTP Status: ${status}")
assert status
}
}
conditions.await(15)
}
def "Test mock user service with GOOD token"() {
given: "A mock user service and an auth verticle"
def conditions = new AsyncConditions(1)
when: "We send a message to the verticle, we expect a positive result"
vertx.eventBus().send('cc.v5.auth.user', GOOD_TOKEN) { reply1 ->
conditions.evaluate {
def status = reply1.succeeded()
LOG.debug("GOOD Status: ${status}")
assert status
}
}
then:
conditions.await(5)
noExceptionThrown()
}
def "Test mock user service with BAD token"() {
given: "A mock user service and an auth verticle"
def conditions = new AsyncConditions(1)
when: "We send a message to the verticle, we expect negative result"
vertx.eventBus().send('cc.v5.auth.user', BAD_TOKEN) { reply2 ->
conditions.evaluate {
def status = reply2.failed()
LOG.debug("BAD Status: ${status}")
assert status
}
}
then:
conditions.await(5)
noExceptionThrown()
}
def cleanupSpec() {
def conditions = new AsyncConditions(1)
vertx.close() { res3 ->
conditions.evaluate {
def status = res3.succeeded()
LOG.debug("NO Status: ${status}")
assert status
}
}
conditions.await(5)
}
}