Merge "Exception for URI /restconf/operations/module_name:rpc ended with slash"
[controller.git] / opendaylight / netconf / config-persister-impl / src / test / java / org / opendaylight / controller / netconf / persist / impl / osgi / TestingExceptionHandler.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.netconf.persist.impl.osgi;
9
10 import org.junit.matchers.JUnitMatchers;
11
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertNull;
15 import static org.junit.Assert.assertThat;
16 import static org.junit.Assert.fail;
17
18 final class TestingExceptionHandler implements Thread.UncaughtExceptionHandler {
19
20     private Throwable t;
21
22     @Override
23     public void uncaughtException(Thread t, Throwable e) {
24         this.t = e;
25     }
26
27     public void assertException(String failMessageSuffix, Class<? extends Exception> exType, String exMessageToContain) {
28         if(t == null) {
29             fail("Should fail to " + failMessageSuffix);
30         }
31         else {
32             assertException(t, exType, exMessageToContain);
33         }
34     }
35
36     public void assertNoException() {
37         assertNull("No exception expected but was " + t, t);
38     }
39
40     private void assertException(Throwable t, Class<? extends Exception> exType, String exMessageToContain) {
41         assertEquals("Expected exception of type " + exType + " but was " + t, exType, t.getClass());
42         if(exMessageToContain!=null) {
43             assertThat(t.getMessage(), JUnitMatchers.containsString(exMessageToContain));
44         }
45     }
46
47     public void assertException(String failMessageSuffix, Class<? extends Exception> exType,
48             String exMessageToContain, Class<? extends Exception> nestedExType, String nestedExMessageToContain,
49             int nestedExDepth) {
50         assertException(failMessageSuffix, exType, exMessageToContain);
51         assertNotNull("Expected nested exception in " + t, t.getCause());
52         assertException(getNestedException(t, nestedExDepth), nestedExType, nestedExMessageToContain);
53     }
54
55     private Throwable getNestedException(Throwable t, int nestedExDepth) {
56
57         int depth = 0;
58         while(t.getCause() != null) {
59             t = t.getCause();
60             depth++;
61             if(nestedExDepth == depth)
62                 return t;
63         }
64         throw new IllegalArgumentException("Unable to get nested exception from " + t + " from depth " + nestedExDepth);
65     }
66 }