1   /*
2    * Copyright (C) 2010 Atlassian
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.atlassian.jira.rest.client;
18  
19  import com.atlassian.jira.rest.client.domain.Transition;
20  import com.sun.jersey.api.client.UniformInterfaceException;
21  import junit.framework.Assert;
22  import org.joda.time.DateTime;
23  import org.joda.time.DateTimeZone;
24  import org.joda.time.format.DateTimeFormatter;
25  import org.joda.time.format.ISODateTimeFormat;
26  
27  import javax.annotation.Nullable;
28  import javax.ws.rs.core.Response;
29  import javax.ws.rs.core.UriBuilder;
30  import java.net.URI;
31  
32  public class TestUtil {
33  	private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
34  	private static DateTimeFormatter dateFormatter = ISODateTimeFormat.date();
35  
36  	public static URI toUri(String str) {
37  		return UriBuilder.fromUri(str).build();
38  	}
39  
40  	public static DateTime toDateTime(String isoDateTimeSt) {
41  		return formatter.parseDateTime(isoDateTimeSt);
42  	}
43  
44  	@SuppressWarnings("unused")
45  	public static DateTime toDateTime(String isoDateTimeSt, DateTimeZone zone) {
46  		return formatter.withZone(zone).parseDateTime(isoDateTimeSt);
47  	}
48  
49  	public static DateTime toDateTimeFromIsoDate(String isoDate) {
50  		return dateFormatter.parseDateTime(isoDate);
51  	}
52  
53  	public static void assertErrorCode(int errorCode, Runnable runnable) {
54  		assertErrorCode(errorCode, null, runnable);
55  	}
56  
57  	@SuppressWarnings("unused")
58  	public static <T extends Throwable> void assertThrows(Class<T> clazz, String regexp, Runnable runnable) {
59  		try {
60  			runnable.run();
61  			Assert.fail(clazz.getName() + " exception expected");
62  		} catch (Throwable e) {
63  			Assert.assertTrue("Expected exception of class " + clazz.getName() + " but was caught " + e.getClass().getName(),
64  					clazz.isInstance(e));
65  			if (e.getMessage() == null && regexp != null) {
66  				Assert.fail("Exception with no message caught, while expected regexp [" + regexp + "]");
67  			}
68  			if (regexp != null && e.getMessage() != null) {
69  				Assert.assertTrue("Message [" + e.getMessage() + "] does not match regexp [" + regexp + "]", e.getMessage().matches(regexp));
70  			}
71  		}
72  
73  	}
74  
75  
76  	public static void assertErrorCode(Response.Status status, String message, Runnable runnable) {
77  		assertErrorCode(status.getStatusCode(), message, runnable);
78  	}
79  
80  	public static void assertErrorCodeWithRegexp(Response.Status status, String regexp, Runnable runnable) {
81  		assertErrorCodeWithRegexp(status.getStatusCode(), regexp, runnable);
82  	}
83  
84  	public static void assertErrorCode(Response.Status status, Runnable runnable) {
85  		assertErrorCode(status.getStatusCode(), null, runnable);
86  	}
87  
88  	public static void assertErrorCode(int errorCode, String message, Runnable runnable) {
89  		try {
90  			runnable.run();
91  			Assert.fail(UniformInterfaceException.class + " exception expected");
92  		} catch (UniformInterfaceException e) {
93  			final String msg = e.getResponse().getEntity(String.class);
94  			if (errorCode != e.getResponse().getStatus()) {
95  				Assert.fail("Unexpected error code and message [" + msg
96  						+ "]. Expected [" + errorCode + "], actual [" + e.getResponse().getStatus() + "]");
97  			}
98  //			Assert.assertEquals(errorCode, );
99  		} catch (RestClientException e) {
100 			Assert.assertTrue("Expected UniformInterfaceException cause, but was [" + e.getCause() + "]", e.getCause() instanceof UniformInterfaceException);
101 			Assert.assertEquals(errorCode, ((UniformInterfaceException) e.getCause()).getResponse().getStatus());
102 			if (message != null) {
103 				Assert.assertEquals(message, e.getMessage());
104 			}
105 		}
106 	}
107 
108 	public static void assertErrorCodeWithRegexp(int errorCode, String regExp, Runnable runnable) {
109 		try {
110 			runnable.run();
111 			Assert.fail(UniformInterfaceException.class + " exception expected");
112 		} catch (UniformInterfaceException e) {
113 			Assert.assertEquals(errorCode, e.getResponse().getStatus());
114 		} catch (RestClientException e) {
115 			Assert.assertTrue(e.getCause() instanceof UniformInterfaceException);
116 			Assert.assertEquals(errorCode, ((UniformInterfaceException) e.getCause()).getResponse().getStatus());
117 			Assert.assertTrue("'" + e.getMessage() + "' does not match regexp '" + regExp + "'", e.getMessage().matches(regExp));
118 		}
119 	}
120 
121 
122 	public static String getLastPathSegment(URI uri) {
123 		final String path = uri.getPath();
124 		final int index = path.lastIndexOf('/');
125 		if (index == -1) {
126 			return path;
127 		}
128 		if (index == path.length()) {
129 			return "";
130 		}
131 		return path.substring(index + 1);
132 	}
133 
134 	public static <E> void assertEqualsSymmetrical(E a, E b) {
135 		Assert.assertEquals(a, b);
136 		Assert.assertEquals(b, a);
137 	}
138 
139 	public static <E> void assertNotEquals(E a, E b) {
140 		if (a == null) {
141 			Assert.assertFalse("[" + a + "] not equals [" + b + "]", b.equals(a));
142 		} else if (b == null) {
143 			Assert.assertFalse("[" + a + "] not equals [" + b + "]", a.equals(b));
144 		} else if (a.equals(b) || b.equals(a)) {
145 			Assert.fail("[" + a + "] not equals [" + b + "]");
146 		}
147 	}
148 
149 	@Nullable
150 	public static Transition getTransitionByName(Iterable<Transition> transitions, String transitionName) {
151 		Transition transitionFound = null;
152 		for (Transition transition : transitions) {
153 			if (transition.getName().equals(transitionName)) {
154 				transitionFound = transition;
155 				break;
156 			}
157 		}
158 		return transitionFound;
159 	}
160 }