001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.testng;
018
019 import java.io.File;
020 import java.util.Collection;
021 import java.util.List;
022 import java.util.Locale;
023
024 import org.apache.camel.CamelContext;
025 import org.apache.camel.Channel;
026 import org.apache.camel.Endpoint;
027 import org.apache.camel.Exchange;
028 import org.apache.camel.Expression;
029 import org.apache.camel.InvalidPayloadException;
030 import org.apache.camel.Message;
031 import org.apache.camel.Predicate;
032 import org.apache.camel.Processor;
033 import org.apache.camel.Route;
034 import org.apache.camel.builder.Builder;
035 import org.apache.camel.builder.RouteBuilder;
036 import org.apache.camel.builder.ValueBuilder;
037 import org.apache.camel.impl.DefaultCamelContext;
038 import org.apache.camel.impl.DefaultExchange;
039 import org.apache.camel.processor.DelegateProcessor;
040 import org.apache.camel.util.ExchangeHelper;
041 import org.apache.camel.util.PredicateAssertHelper;
042 import org.slf4j.Logger;
043 import org.slf4j.LoggerFactory;
044 import org.testng.Assert;
045
046 /**
047 * A bunch of useful testing methods
048 *
049 * @version $Revision: 1172774 $
050 */
051 public abstract class TestSupport extends Assert {
052 protected static final String LS = System.getProperty("line.separator");
053 private static final Logger LOG = LoggerFactory.getLogger(TestSupport.class);
054 protected transient Logger log = LoggerFactory.getLogger(getClass());
055
056 // Builder methods for expressions used when testing
057 // -------------------------------------------------------------------------
058
059 /**
060 * Returns a value builder for the given header
061 */
062 public static ValueBuilder header(String name) {
063 return Builder.header(name);
064 }
065
066 /**
067 * Returns a value builder for the given property
068 */
069 public static ValueBuilder property(String name) {
070 return Builder.property(name);
071 }
072
073 /**
074 * Returns a predicate and value builder for the inbound body on an exchange
075 */
076 public static ValueBuilder body() {
077 return Builder.body();
078 }
079
080 /**
081 * Returns a predicate and value builder for the inbound message body as a
082 * specific type
083 */
084 public static <T> ValueBuilder bodyAs(Class<T> type) {
085 return Builder.bodyAs(type);
086 }
087
088 /**
089 * Returns a predicate and value builder for the outbound body on an
090 * exchange
091 */
092 public static ValueBuilder outBody() {
093 return Builder.outBody();
094 }
095
096 /**
097 * Returns a predicate and value builder for the outbound message body as a
098 * specific type
099 */
100 public static <T> ValueBuilder outBodyAs(Class<T> type) {
101 return Builder.outBodyAs(type);
102 }
103
104 /**
105 * Returns a predicate and value builder for the fault body on an
106 * exchange
107 */
108 public static ValueBuilder faultBody() {
109 return Builder.faultBody();
110 }
111
112 /**
113 * Returns a predicate and value builder for the fault message body as a
114 * specific type
115 */
116 public static <T> ValueBuilder faultBodyAs(Class<T> type) {
117 return Builder.faultBodyAs(type);
118 }
119
120 /**
121 * Returns a value builder for the given system property
122 */
123 public static ValueBuilder systemProperty(String name) {
124 return Builder.systemProperty(name);
125 }
126
127 /**
128 * Returns a value builder for the given system property
129 */
130 public static ValueBuilder systemProperty(String name, String defaultValue) {
131 return Builder.systemProperty(name, defaultValue);
132 }
133
134 // Assertions
135 // -----------------------------------------------------------------------
136
137 public static <T> T assertIsInstanceOf(Class<T> expectedType, Object value) {
138 assertNotNull(value, "Expected an instance of type: " + expectedType.getName() + " but was null");
139 assertTrue(expectedType.isInstance(value), "object should be a " + expectedType.getName()
140 + " but was: " + value + " with type: " + value.getClass().getName());
141 return expectedType.cast(value);
142 }
143
144 public static void assertEndpointUri(Endpoint endpoint, String uri) {
145 assertNotNull(endpoint, "Endpoint is null when expecting endpoint for: " + uri);
146 assertEquals(endpoint.getEndpointUri(), uri, "Endoint uri for: " + endpoint);
147 }
148
149 /**
150 * Asserts the In message on the exchange contains the expected value
151 */
152 public static Object assertInMessageHeader(Exchange exchange, String name, Object expected) {
153 return assertMessageHeader(exchange.getIn(), name, expected);
154 }
155
156 /**
157 * Asserts the Out message on the exchange contains the expected value
158 */
159 public static Object assertOutMessageHeader(Exchange exchange, String name, Object expected) {
160 return assertMessageHeader(exchange.getOut(), name, expected);
161 }
162
163 /**
164 * Asserts that the given exchange has an OUT message of the given body value
165 *
166 * @param exchange the exchange which should have an OUT message
167 * @param expected the expected value of the OUT message
168 * @throws InvalidPayloadException is thrown if the payload is not the expected class type
169 */
170 public static void assertInMessageBodyEquals(Exchange exchange, Object expected) throws InvalidPayloadException {
171 assertNotNull(exchange, "Should have a response exchange!");
172
173 Object actual;
174 if (expected == null) {
175 actual = ExchangeHelper.getMandatoryInBody(exchange);
176 assertEquals(actual, expected, "in body of: " + exchange);
177 } else {
178 actual = ExchangeHelper.getMandatoryInBody(exchange, expected.getClass());
179 }
180 assertEquals(actual, expected, "in body of: " + exchange);
181
182 LOG.debug("Received response: " + exchange + " with in: " + exchange.getIn());
183 }
184
185 /**
186 * Asserts that the given exchange has an OUT message of the given body value
187 *
188 * @param exchange the exchange which should have an OUT message
189 * @param expected the expected value of the OUT message
190 * @throws InvalidPayloadException is thrown if the payload is not the expected class type
191 */
192 public static void assertOutMessageBodyEquals(Exchange exchange, Object expected) throws InvalidPayloadException {
193 assertNotNull(exchange, "Should have a response exchange!");
194
195 Object actual;
196 if (expected == null) {
197 actual = ExchangeHelper.getMandatoryOutBody(exchange);
198 assertEquals(actual, expected, "output body of: " + exchange);
199 } else {
200 actual = ExchangeHelper.getMandatoryOutBody(exchange, expected.getClass());
201 }
202 assertEquals(actual, expected, "output body of: " + exchange);
203
204 LOG.debug("Received response: " + exchange + " with out: " + exchange.getOut());
205 }
206
207 public static Object assertMessageHeader(Message message, String name, Object expected) {
208 Object value = message.getHeader(name);
209 assertEquals(value, expected, "Header: " + name + " on Message: " + message);
210 return value;
211 }
212
213 /**
214 * Asserts that the given expression when evaluated returns the given answer
215 */
216 public static Object assertExpression(Expression expression, Exchange exchange, Object expected) {
217 Object value;
218 if (expected != null) {
219 value = expression.evaluate(exchange, expected.getClass());
220 } else {
221 value = expression.evaluate(exchange, Object.class);
222 }
223
224 LOG.debug("Evaluated expression: " + expression + " on exchange: " + exchange + " result: " + value);
225
226 assertEquals(value, expected, "Expression: " + expression + " on Exchange: " + exchange);
227 return value;
228 }
229
230 /**
231 * Asserts that the predicate returns the expected value on the exchange
232 */
233 public static void assertPredicateMatches(Predicate predicate, Exchange exchange) {
234 assertPredicate(predicate, exchange, true);
235 }
236
237 /**
238 * Asserts that the predicate returns the expected value on the exchange
239 */
240 public static void assertPredicateDoesNotMatch(Predicate predicate, Exchange exchange) {
241 try {
242 PredicateAssertHelper.assertMatches(predicate, "Predicate should match: ", exchange);
243 } catch (AssertionError e) {
244 LOG.debug("Caught expected assertion error: " + e);
245 }
246 assertPredicate(predicate, exchange, false);
247 }
248
249 /**
250 * Asserts that the predicate returns the expected value on the exchange
251 */
252 public static boolean assertPredicate(final Predicate predicate, Exchange exchange, boolean expected) {
253 if (expected) {
254 PredicateAssertHelper.assertMatches(predicate, "Predicate failed: ", exchange);
255 }
256 boolean value = predicate.matches(exchange);
257
258 LOG.debug("Evaluated predicate: " + predicate + " on exchange: " + exchange + " result: " + value);
259
260 assertEquals(value, expected, "Predicate: " + predicate + " on Exchange: " + exchange);
261 return value;
262 }
263
264 /**
265 * Resolves an endpoint and asserts that it is found
266 */
267 public static Endpoint resolveMandatoryEndpoint(CamelContext context, String uri) {
268 Endpoint endpoint = context.getEndpoint(uri);
269
270 assertNotNull(endpoint, "No endpoint found for URI: " + uri);
271
272 return endpoint;
273 }
274
275 /**
276 * Resolves an endpoint and asserts that it is found
277 */
278 public static <T extends Endpoint> T resolveMandatoryEndpoint(CamelContext context, String uri,
279 Class<T> endpointType) {
280 T endpoint = context.getEndpoint(uri, endpointType);
281
282 assertNotNull(endpoint, "No endpoint found for URI: " + uri);
283
284 return endpoint;
285 }
286
287 /**
288 * Creates an exchange with the given body
289 */
290 protected Exchange createExchangeWithBody(CamelContext camelContext, Object body) {
291 Exchange exchange = new DefaultExchange(camelContext);
292 Message message = exchange.getIn();
293 message.setHeader("testClass", getClass().getName());
294 message.setBody(body);
295 return exchange;
296 }
297
298 public static <T> T assertOneElement(List<T> list) {
299 assertEquals(list.size(), 1, "Size of list should be 1: " + list);
300 return list.get(0);
301 }
302
303 /**
304 * Asserts that a list is of the given size
305 */
306 public static <T> List<T> assertListSize(List<T> list, int size) {
307 return assertListSize("List", list, size);
308 }
309
310 /**
311 * Asserts that a list is of the given size
312 */
313 public static <T> List<T> assertListSize(String message, List<T> list, int size) {
314 assertEquals(list.size(), size, message + " should be of size: " + size + " but is: " + list);
315 return list;
316 }
317
318 /**
319 * Asserts that a list is of the given size
320 */
321 public static <T> Collection<T> assertCollectionSize(Collection<T> list, int size) {
322 return assertCollectionSize("List", list, size);
323 }
324
325 /**
326 * Asserts that a list is of the given size
327 */
328 public static <T> Collection<T> assertCollectionSize(String message, Collection<T> list, int size) {
329 assertEquals(list.size(), size, message + " should be of size: " + size + " but is: " + list);
330 return list;
331 }
332
333 /**
334 * A helper method to create a list of Route objects for a given route builder
335 */
336 public static List<Route> getRouteList(RouteBuilder builder) throws Exception {
337 CamelContext context = new DefaultCamelContext();
338 context.addRoutes(builder);
339 context.start();
340 List<Route> answer = context.getRoutes();
341 context.stop();
342 return answer;
343 }
344
345 /**
346 * Asserts that the text contains the given string
347 *
348 * @param text the text to compare
349 * @param containedText the text which must be contained inside the other text parameter
350 */
351 public static void assertStringContains(String text, String containedText) {
352 assertNotNull(text, "Text should not be null!");
353 assertTrue(text.contains(containedText), "Text: " + text + " does not contain: " + containedText);
354 }
355
356 /**
357 * If a processor is wrapped with a bunch of DelegateProcessor or DelegateAsyncProcessor objects
358 * this call will drill through them and return the wrapped Processor.
359 */
360 public static Processor unwrap(Processor processor) {
361 while (true) {
362 if (processor instanceof DelegateProcessor) {
363 processor = ((DelegateProcessor)processor).getProcessor();
364 } else {
365 return processor;
366 }
367 }
368 }
369
370 /**
371 * If a processor is wrapped with a bunch of DelegateProcessor or DelegateAsyncProcessor objects
372 * this call will drill through them and return the Channel.
373 * <p/>
374 * Returns null if no channel is found.
375 */
376 public static Channel unwrapChannel(Processor processor) {
377 while (true) {
378 if (processor instanceof Channel) {
379 return (Channel) processor;
380 } else if (processor instanceof DelegateProcessor) {
381 processor = ((DelegateProcessor)processor).getProcessor();
382 } else {
383 return null;
384 }
385 }
386 }
387
388 /**
389 * Recursively delete a directory, useful to zapping test data
390 *
391 * @param file the directory to be deleted
392 */
393 public static void deleteDirectory(String file) {
394 deleteDirectory(new File(file));
395 }
396
397 /**
398 * Recursively delete a directory, useful to zapping test data
399 *
400 * @param file the directory to be deleted
401 */
402 public static void deleteDirectory(File file) {
403 if (file.isDirectory()) {
404 File[] files = file.listFiles();
405 for (int i = 0; i < files.length; i++) {
406 deleteDirectory(files[i]);
407 }
408 }
409
410 if (file.exists()) {
411 assertTrue(file.delete(), "Deletion of file: " + file.getAbsolutePath() + " failed");
412 }
413 }
414
415 /**
416 * create the directory
417 *
418 * @param file the directory to be created
419 */
420 public static void createDirectory(String file) {
421 File dir = new File(file);
422 dir.mkdirs();
423 }
424
425 /**
426 * To be used for folder/directory comparison that works across different platforms such
427 * as Window, Mac and Linux.
428 */
429 public static void assertDirectoryEquals(String expected, String actual) {
430 assertDirectoryEquals(null, expected, actual);
431 }
432
433 /**
434 * To be used for folder/directory comparison that works across different platforms such
435 * as Window, Mac and Linux.
436 */
437 public static void assertDirectoryEquals(String message, String expected, String actual) {
438 // must use single / as path separators
439 String expectedPath = expected.replace('\\', '/');
440 String actualPath = actual.replace('\\', '/');
441
442 if (message != null) {
443 assertEquals(actualPath, expectedPath, message);
444 } else {
445 assertEquals(actualPath, expectedPath);
446 }
447 }
448
449 /**
450 * To be used to check is a file is found in the file system
451 */
452 public static void assertFileExists(String filename) {
453 File file = new File(filename).getAbsoluteFile();
454 assertTrue(file.exists(), "File " + filename + " should exist");
455 }
456
457 /**
458 * Is this OS the given platform.
459 * <p/>
460 * Uses <tt>os.name</tt> from the system properties to determine the OS.
461 *
462 * @param platform such as Windows
463 * @return <tt>true</tt> if its that platform.
464 */
465 public static boolean isPlatform(String platform) {
466 String osName = System.getProperty("os.name").toLowerCase(Locale.US);
467 return osName.indexOf(platform.toLowerCase(Locale.US)) > -1;
468 }
469
470 /**
471 * Is this Java by the given vendor.
472 * <p/>
473 * Uses <tt>java.vendor</tt> from the system properties to determine the vendor.
474 *
475 * @param vendor such as IBM
476 * @return <tt>true</tt> if its that vendor.
477 */
478 public static boolean isJavaVendor(String vendor) {
479 String javaVendor = System.getProperty("java.vendor").toLowerCase(Locale.US);
480 return javaVendor.indexOf(vendor.toLowerCase(Locale.US)) > -1;
481 }
482
483 /**
484 * Is this Java 1.5
485 *
486 * @return <tt>true</tt> if its Java 1.5, <tt>false</tt> if its not (for example Java 1.6 or better)
487 * @deprecated will be removed in the near future as Camel now requires JDK1.6+
488 */
489 @Deprecated
490 public static boolean isJava15() {
491 String javaVersion = System.getProperty("java.version").toLowerCase(Locale.US);
492 return javaVersion.startsWith("1.5");
493 }
494
495 public String getTestMethodName() {
496 return "";
497 }
498
499 }