@Test @DirtiesContext public void testMocksAreValid() throws Exception { result.setExpectedCount(1); ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); producerTemplate.sendBody("direct:start", Util.generateMockTwitterStatus()); MockEndpoint.assertIsSatisfied(camelContext); Object body = result.getExchanges().get(0).getIn().getBody(); assertEquals(String.class, body.getClass()); ObjectMapper mapper = new ObjectMapper(); JsonNode outJson = mapper.readTree((String)body); assertEquals("Bob", outJson.get("FirstName").asText()); assertEquals("Vila", outJson.get("LastName").asText()); assertEquals("bobvila1982", outJson.get("Title").asText()); assertEquals("Let's build a house!", outJson.get("Description").asText()); }
@Test @DirtiesContext public void testMocksAreValid() throws Exception { result.setExpectedCount(1); ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); producerTemplate.sendBody("direct:start", Util.generateMockTwitterStatus()); MockEndpoint.assertIsSatisfied(camelContext); Object body = result.getExchanges().get(0).getIn().getBody(); assertEquals(String.class, body.getClass()); ObjectMapper mapper = new ObjectMapper(); JsonNode sfJson = mapper.readTree((String)body); assertNotNull(sfJson.get("TwitterScreenName__c")); assertEquals("bobvila1982", sfJson.get("TwitterScreenName__c").asText()); }
@Test @DirtiesContext public void testSeparateNotSucceed() throws Exception { result.setExpectedCount(1); ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); Status s = Util.generateMockTwitterStatus(); when(s.getUser().getName()).thenReturn("BobVila"); producerTemplate.sendBody("direct:start", s); MockEndpoint.assertIsSatisfied(camelContext); Object body = result.getExchanges().get(0).getIn().getBody(); assertEquals(String.class, body.getClass()); ObjectMapper mapper = new ObjectMapper(); JsonNode outJson = mapper.readTree((String)body); assertEquals("BobVila", outJson.get("FirstName").asText()); assertNull(outJson.get("LastName")); assertEquals("bobvila1982", outJson.get("Title").asText()); assertEquals("Let's build a house!", outJson.get("Description").asText()); }
@Test public void testStep() throws Exception { List<String> allMessages = new ArrayList<>(matchedJames); allMessages.addAll(matchedJimmi); allMessages.addAll(otherwiseMessages); matchedEndpoint.expectedBodiesReceived(matchedJames); matchedJimmiEndpoint.expectedBodiesReceived(matchedJimmi); otherwiseEndpoint.expectedBodiesReceived(otherwiseMessages); allMessagesEndpoint.expectedBodiesReceived(allMessages); for (Object body : allMessages) { template.sendBody(START_URI, body); } MockEndpoint[] mockEndpoints = { matchedEndpoint, matchedJimmiEndpoint, otherwiseEndpoint, allMessagesEndpoint }; MockEndpoint.assertIsSatisfied(mockEndpoints); logMessagesReceived(mockEndpoints); }
@Test public void testStep() throws Exception { List<String> allMessages = new ArrayList<>(matchingMessages); allMessages.addAll(notMatchingMessages); matchedEndpoint.expectedBodiesReceived(matchingMessages); allMessagesEndpoint.expectedBodiesReceived(allMessages); for (Object body : allMessages) { template.sendBody(START_URI, body); } MockEndpoint[] mockEndpoints = { matchedEndpoint, allMessagesEndpoint }; MockEndpoint.assertIsSatisfied(mockEndpoints); logMessagesReceived(mockEndpoints); }
@Test public void testGrabbingListOfEntries() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); // as the default delay option is one hour long, we expect exactly one message exchange mock.expectedMessageCount(1); // give the route a bit time to start and fetch the weather info assertMockEndpointsSatisfied(20, TimeUnit.SECONDS); Exchange exchange = mock.getExchanges().get(0); assertNotNull(exchange); Message in = exchange.getIn(); assertNotNull(in); String weather = assertIsInstanceOf(String.class, in.getBody()); checkWeatherContent(weather); }
@Test public void testSimpleBody() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); Project pojo = new Project(); pojo.setLicense("XXX"); template.sendBody("direct:simple", pojo); mock.assertIsSatisfied(); // the result is a List List<?> received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody()); // and each row in the list is a Map Map<?, ?> row = assertIsInstanceOf(Map.class, received.get(0)); // and we should be able the get the project from the map that should be Linux assertEquals("Linux", row.get("PROJECT")); }
@Test public void testNonJmsDeliveryModePreserveQos() throws InterruptedException { MockEndpoint mock = getMockEndpoint("mock:bar"); mock.expectedBodiesReceived("Beer is good..."); // in this test, we can only pass if we are "preserving" existing deliveryMode. // this means camel expects to have an existing QoS set as a header, or it will pick // from the JMS message created by the message creator // otherwise, "preserveMessageQos==true" does not allow us to explicity set the deliveryMode // on the message mock.message(0).header("JMSDeliveryMode").isEqualTo(1); template.sendBodyAndHeader("direct:preserveQosNonJmsDeliveryMode", "Beer is good...", JmsConstants.JMS_DELIVERY_MODE, 3); assertMockEndpointsSatisfied(); }
public void testBurstySampling() throws Exception { NotifyBuilder notify = new NotifyBuilder(context).whenDone(5).create(); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(2); mock.setResultWaitTime(3000); List<Exchange> sentExchanges = new ArrayList<Exchange>(); // send a burst of 5 exchanges, expecting only one to get through sendExchangesThroughDroppingThrottler(sentExchanges, 5); // sleep through a complete period Thread.sleep(1100); // send another 5 now sendExchangesThroughDroppingThrottler(sentExchanges, 5); notify.matchesMockWaitTime(); mock.assertIsSatisfied(); validateDroppedExchanges(sentExchanges, mock.getReceivedCounter()); }
private void doSendMessages(int files, int poolSize) throws Exception { MockEndpoint mock = getMockEndpoint("mock:aggregated"); mock.expectedMessageCount(2); mock.setResultWaitTime(30 * 1000L); ExecutorService executor = Executors.newFixedThreadPool(poolSize); for (int i = 0; i < files; i++) { final int index = i; executor.submit(new Callable<Object>() { public Object call() throws Exception { String id = index % 2 == 0 ? "A" : "B"; template.sendBodyAndHeader("direct:start", index, "id", id); // simulate a little delay Thread.sleep(3); return null; } }); } assertMockEndpointsSatisfied(); executor.shutdownNow(); }
@Test public void testJmsPollingConsumerLowTimeout() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello Claus"); // use another thread for polling consumer to demonstrate that we can wait before // the message is sent to the queue Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { String body = consumer.receiveBody("activemq:queue.start", 100, String.class); assertNull("Should be null", body); template.sendBody("activemq:queue.foo", "Hello Claus"); } }); // wait a little to demonstrate we can start poll before we have a msg on the queue Thread.sleep(500); template.sendBody("direct:start", "Hello"); assertMockEndpointsSatisfied(); }
@Test public void testCached() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello London"); template.sendBodyAndHeader("direct:b", "Body", "name", "London"); mock.assertIsSatisfied(); // now change content in the file in the classpath and try again template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/freemarker?fileExist=Override", "Bye ${headers.name}", Exchange.FILE_NAME, "hello.ftl"); mock.reset(); // we must expected the original filecontent as the cache is enabled, so its Hello and not Bye mock.expectedBodiesReceived("Hello Paris"); template.sendBodyAndHeader("direct:b", "Body", "name", "Paris"); mock.assertIsSatisfied(); }
/** * When the setting useMessageIdAsCorrelationid is true and * a correlation id is set on the message then we expect the reply * to contain the messageId of the sent message. Here we test only that * it is not the correlation id given as the messageId is not know * beforehand. */ @Test public void testRequestReplyCorrelationByMessageId() throws Exception { MockEndpoint result = getMockEndpoint("mock:result"); result.expectedMessageCount(1); Exchange out = template.send("jms2:queue:hello2", ExchangePattern.InOut, new Processor() { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); in.setBody("Hello World"); in.setHeader("JMSCorrelationID", "a"); } }); result.assertIsSatisfied(); assertNotNull(out); assertEquals(REPLY_BODY, out.getOut().getBody(String.class)); assertEquals("a", out.getOut().getHeader("JMSCorrelationID")); }
public void testPreMoveSameFileTwice() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); template.sendBodyAndHeader("file://target/premove", "Hello World", Exchange.FILE_NAME, "hello.txt"); assertMockEndpointsSatisfied(); oneExchangeDone.matchesMockWaitTime(); // reset and drop the same file again mock.reset(); mock.expectedBodiesReceived("Hello Again World"); template.sendBodyAndHeader("file://target/premove", "Hello Again World", Exchange.FILE_NAME, "hello.txt"); assertMockEndpointsSatisfied(); }
@Test public void testSendA01() throws Exception { MockEndpoint mock = getMockEndpoint("mock:a01"); mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(Message.class); String line1 = "MSH|^~\\&|MYSENDER|MYSENDERAPP|MYCLIENT|MYCLIENTAPP|200612211200||ADT^A01|123|P|2.4"; String line2 = "PID|||123456||Doe^John"; StringBuilder in = new StringBuilder(); in.append(line1); in.append("\r"); in.append(line2); String out = template.requestBody("mina2:tcp://127.0.0.1:" + getPort() + "?sync=true&codec=#hl7codec", in.toString(), String.class); String[] lines = out.split("\r"); assertEquals("MSH|^~\\&|MYSENDER||||200701011539||ADT^A01||||123", lines[0]); assertEquals("PID|||123||Doe^John", lines[1]); assertMockEndpointsSatisfied(); }
@Test public void testQuartzCronRoute() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); QuartzComponent component = context.getComponent("quartz2", QuartzComponent.class); Scheduler scheduler = component.getScheduler(); // collect all jobKeys of this route (ideally only one). ArrayList<JobKey> jobKeys = new ArrayList<JobKey>(); for (String group : scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(group))) { jobKeys.add(jobKey); } } JobDataMap jobDataMap = scheduler.getJobDetail(jobKeys.get(0)).getJobDataMap(); // trigger job manually scheduler.triggerJob(jobKeys.get(0), jobDataMap); assertMockEndpointsSatisfied(); }
public void testAggregateFromWireTap() throws Exception { MockEndpoint end = getMockEndpoint("mock:end"); end.expectedBodiesReceived("A", "B"); MockEndpoint aggregated = getMockEndpoint("mock:aggregated"); aggregated.expectedMessageCount(1); template.sendBody("direct:start", "A"); template.sendBody("direct:start", "B"); assertMockEndpointsSatisfied(); String body = aggregated.getReceivedExchanges().get(0).getIn().getBody(String.class); // should be either AB or BA (wiretap can be run out of order) assertTrue("Should be AB or BA, was: " + body, "AB".equals(body) || "BA".equals(body)); }
@Test public void testNotCached() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello London"); template.sendBodyAndHeader("direct:a", "Body", "name", "London"); mock.assertIsSatisfied(); // now change content in the file in the classpath and try again template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/freemarker?fileExist=Override", "Bye ${headers.name}", Exchange.FILE_NAME, "hello.ftl"); mock.reset(); mock.expectedBodiesReceived("Bye Paris"); template.sendBodyAndHeader("direct:a", "Body", "name", "Paris"); mock.assertIsSatisfied(); }
@Test public void testInvokingOneWayServiceFromCXFClient() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedFileExists("target/camel-file/cxf-oneway-route"); Greeter client = getCXFClient(); client.greetMeOneWay("lemac"); // may need to wait until the oneway call completes long waitUntil = System.currentTimeMillis() + 10000; while (!bindingDone && System.currentTimeMillis() < waitUntil) { Thread.sleep(1000); } assertMockEndpointsSatisfied(); assertNull("exception occured: " + bindingException, bindingException); }
@Test public void testHttpGetWithExplicitStreamClose() throws Exception { // We close connections explicitely at the very end of the flow // (camel doesn't know when the stream is not needed any more) MockEndpoint mockEndpoint = resolveMandatoryEndpoint("mock:results", MockEndpoint.class); for (int i = 0; i < 5; i++) { mockEndpoint.expectedMessageCount(1); template.sendBody("seda:withoutConversion?concurrentConsumers=5", null); mockEndpoint.assertIsSatisfied(); Object response = mockEndpoint.getReceivedExchanges().get(0).getIn().getBody(); InputStream responseStream = assertIsInstanceOf(InputStream.class, response); responseStream.close(); mockEndpoint.reset(); } }
@Test public void testDeleteOnFailure() throws Exception { shouldIdie = true; final long jobId = 111; final byte[] payload = Helper.stringToBytes(testMessage); final Job jobMock = mock(Job.class); when(jobMock.getJobId()).thenReturn(jobId); when(jobMock.getData()).thenReturn(payload); when(client.reserve(anyInt())) .thenReturn(jobMock) .thenReturn(null); MockEndpoint result = getMockEndpoint("mock:result"); result.expectedMinimumMessageCount(1); result.assertIsNotSatisfied(1000); verify(client, atLeastOnce()).reserve(anyInt()); verify(client, atLeast(1)).delete(jobId); }
public void testRecipientExchangeProperty() throws Exception { getMockEndpoint("mock:a").expectedPropertyReceived(Exchange.RECIPIENT_LIST_ENDPOINT, "direct://a"); getMockEndpoint("mock:a").expectedPropertyReceived(Exchange.TO_ENDPOINT, "mock://a"); getMockEndpoint("mock:b").expectedPropertyReceived(Exchange.RECIPIENT_LIST_ENDPOINT, "direct://b"); getMockEndpoint("mock:b").expectedPropertyReceived(Exchange.TO_ENDPOINT, "mock://b"); getMockEndpoint("mock:c").expectedPropertyReceived(Exchange.RECIPIENT_LIST_ENDPOINT, "direct://c"); getMockEndpoint("mock:c").expectedPropertyReceived(Exchange.TO_ENDPOINT, "mock://c"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello c"); // would be the last one mock.expectedPropertyReceived(Exchange.RECIPIENT_LIST_ENDPOINT, "direct://c"); String out = template.requestBodyAndHeader("direct:start", "Hello World", "slip", "direct:a,direct:b,direct:c", String.class); assertEquals("Hello c", out); assertMockEndpointsSatisfied(); assertEquals(3, strategy.getUris().size()); assertEquals("direct://a", strategy.getUris().get(0)); assertEquals("direct://b", strategy.getUris().get(1)); assertEquals("direct://c", strategy.getUris().get(2)); }
@Test public void testSimpleConsumerWithEmptySequenceFile() throws Exception { if (!canTest()) { return; } final Path file = new Path(new File("target/test/test-camel-sequence-file").getAbsolutePath()); Configuration conf = new Configuration(); SequenceFile.Writer writer = createWriter(conf, file, NullWritable.class, BooleanWritable.class); writer.sync(); writer.close(); MockEndpoint resultEndpoint = context.getEndpoint("mock:result", MockEndpoint.class); resultEndpoint.expectedMessageCount(0); context.addRoutes(new RouteBuilder() { public void configure() { from("hdfs2:localhost/" + file.toUri() + "?fileSystemType=LOCAL&fileType=SEQUENCE_FILE&chunkSize=4096&initialDelay=0").to("mock:result"); } }); context.start(); resultEndpoint.assertIsSatisfied(); }
public void testToBytes() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("file://target/gf") .convertBodyTo(byte[].class) .to("mock:result"); } }); context.start(); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(byte[].class); mock.message(0).body(String.class).isEqualTo("Hello World"); template.sendBodyAndHeader("file://target/gf", "Hello World", Exchange.FILE_NAME, "hello.txt"); assertMockEndpointsSatisfied(); }
public void testLoadingRouteFromCommand() throws Exception { Main main = new Main(); // let the main load the MyRouteBuilder main.parseArguments(new String[]{"-r", "org.apache.camel.main.MainTest$MyRouteBuilder"}); main.start(); List<CamelContext> contextList = main.getCamelContexts(); assertNotNull(contextList); assertEquals("Did not get the expected count of Camel contexts", 1, contextList.size()); CamelContext camelContext = contextList.get(0); MockEndpoint endpoint = camelContext.getEndpoint("mock:results", MockEndpoint.class); endpoint.expectedMinimumMessageCount(1); main.getCamelTemplate().sendBody("direct:start", "<message>1</message>"); endpoint.assertIsSatisfied(); main.stop(); }
@Test public void testCached() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello London"); template.sendBodyAndHeader("direct:b", "Body", "name", "London"); mock.assertIsSatisfied(); // now change content in the file in the classpath and try again template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/stringtemplate", "Bye <headers.name>", Exchange.FILE_NAME, "hello.tm"); mock.reset(); // we must expected the original filecontent as the cache is enabled, so its Hello and not Bye mock.expectedBodiesReceived("Hello Paris"); template.sendBodyAndHeader("direct:b", "Body", "name", "Paris"); mock.assertIsSatisfied(); }
public void testEnd2FailureTest() throws Exception { MockEndpoint end2 = getMockEndpoint("mock:end2"); end2.whenAnyExchangeReceived(new Processor() { public void process(Exchange exchange) throws Exception { throw new RuntimeException("Simulated Exception"); } }); // we run in parallel so the task could have been submitted so we either get 0 or 1 messages at mock:end1 getMockEndpoint("mock:end1").expectedMinimumMessageCount(0); getMockEndpoint("mock:end3").expectedMessageCount(0); getMockEndpoint("mock:end4").expectedMessageCount(1); String result = template.requestBody("direct:start", "Hello World!", String.class); assertEquals("Stop!", result); assertMockEndpointsSatisfied(); }
public void testFiredInFutureWithTPatternNoPeriod() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { Date future = new Date(new Date().getTime() + 1000); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String time = sdf.format(future); fromF("timer://foo?period=0&time=%s", time).to("mock:result"); } }); context.start(); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); assertMockEndpointsSatisfied(); }
@Test public void testRequestReplyNoMutate() throws Exception { MockEndpoint result = getMockEndpoint("mock:result"); result.expectedMessageCount(1); result.expectedBodiesReceived("Hello World"); result.expectedHeaderReceived("foo", 123); template.send("activemq:queue:hello", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); exchange.getIn().setHeader("foo", 123); } }); result.assertIsSatisfied(); }
public void testLogBodyMaxLengthTest() throws Exception { // create a big body StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { int value = i % 10; sb.append(value); } String body = sb.toString(); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.sendBody("direct:start", body); assertMockEndpointsSatisfied(); // should be empty body as toString on the message will return an empty body TraceExchangeFormatter myFormatter = context.getRegistry().lookupByNameAndType("logFormatter", TraceExchangeFormatter.class); String msg = myFormatter.getMessage(); assertTrue(msg.endsWith("Body: [Body is not logged]]")); // but body and clipped should not be the same assertNotSame("clipped log and real body should not be the same", msg, mock.getReceivedExchanges().get(0).getIn().getBody(String.class)); }
@Test public void testSftpSimpleConsume() throws Exception { if (!canTest()) { return; } String expected = "Hello World"; // create file using regular file template.sendBodyAndHeader("file://" + FTP_ROOT_DIR, expected, Exchange.FILE_NAME, "hello.txt"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedHeaderReceived(Exchange.FILE_NAME, "hello.txt"); mock.expectedBodiesReceived(expected); context.startRoute("foo"); assertMockEndpointsSatisfied(); }
@Test public void testSendWithHeaders() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.message(0).body().isEqualTo("Hello World"); mock.message(0).header("Content-Type").isEqualTo("text/plain"); MockEndpoint copy = getMockEndpoint("mock:copy"); copy.expectedMessageCount(1); copy.message(0).body().isEqualTo("Hello World"); copy.message(0).header("Content-Type").isEqualTo("text/plain"); template.sendBodyAndHeader(uri, "Hello World", "Content-Type", "text/plain"); assertMockEndpointsSatisfied(); }
@Test @DirtiesContext public void testMocksAreValid() throws Exception { result.setExpectedCount(1); final ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); producerTemplate.sendBody("direct:start", new ByteArrayInputStream("{\"field1\":\"value1\"}".getBytes())); MockEndpoint.assertIsSatisfied(camelContext); final Object body = result.getExchanges().get(0).getIn().getBody(); assertEquals(Pojo.class, body.getClass()); assertEquals("value1", ((Pojo) body).getField1()); }
@Test public void testStep() throws Exception { resultsEndpoint.expectedBodiesReceived(expectedMessages); template.sendBody(START_URI, body); MockEndpoint.assertIsSatisfied(resultsEndpoint); logMessagesReceived(resultsEndpoint); }
@Test public void testStepWithCollection() throws Exception { resultsEndpoint.expectedBodiesReceived("a","b","c"); template.sendBody(START_URI, Arrays.asList("a","b","c")); MockEndpoint.assertIsSatisfied(resultsEndpoint); logMessagesReceived(resultsEndpoint); }