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.google.common.base.Predicate;
21  import com.google.common.collect.Iterables;
22  import com.sun.jersey.api.client.UniformInterfaceException;
23  import junit.framework.Assert;
24  import org.joda.time.DateTime;
25  import org.joda.time.format.DateTimeFormatter;
26  import org.joda.time.format.ISODateTimeFormat;
27  
28  import javax.annotation.Nullable;
29  import javax.ws.rs.core.Response;
30  import java.net.URI;
31  import java.net.URISyntaxException;
32  
33  public class TestUtil {
34  	private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
35  
36  	public static URI toUri(String str) {
37  		try {
38  			return new URI(str);
39  		} catch (URISyntaxException e) {
40  			throw new RuntimeException(e);
41  		}
42  	}
43  
44  	public static DateTime toDateTime(String isoDateTimeSt) {
45  		return formatter.parseDateTime(isoDateTimeSt);
46  	}
47  
48  	public static void assertErrorCode(int errorCode, Runnable runnable) {
49  		assertErrorCode(errorCode, null, runnable);
50  	}
51  
52  	public static <T extends Throwable> void assertThrows(Class<T> clazz, String regexp, Runnable runnable) {
53  		try {
54  			runnable.run();
55  			Assert.fail(clazz.getName() + " exception expected");
56  		} catch (Throwable e) {
57  			Assert.assertTrue("Expected exception of class " + clazz.getName() + " but was caught " + e.getClass().getName(),
58  					clazz.isInstance(e));
59  			if (e.getMessage() == null && regexp != null) {
60  				Assert.fail("Exception with no message caught, while expected regexp [" + regexp + "]");
61  			}
62  			if (regexp != null && e.getMessage() != null) {
63  				Assert.assertTrue("Message [" + e.getMessage() + "] does not match regexp [" + regexp + "]", e.getMessage().matches(regexp));
64  			}
65  		}
66  
67  	}
68  
69  
70  	public static void assertErrorCode(Response.Status status, String message, Runnable runnable) {
71  		assertErrorCode(status.getStatusCode(), message, runnable);
72  	}
73  
74  	public static void assertErrorCodeWithRegexp(Response.Status status, String regexp, Runnable runnable) {
75  		assertErrorCodeWithRegexp(status.getStatusCode(), regexp, runnable);
76  	}
77  
78  	public static void assertErrorCode(Response.Status status, Runnable runnable) {
79  		assertErrorCode(status.getStatusCode(), null, runnable);
80  	}
81  
82  	public static void assertErrorCode(int errorCode, String message, Runnable runnable) {
83  		try {
84  			runnable.run();
85  			Assert.fail(UniformInterfaceException.class + " exception expected");
86  		} catch (UniformInterfaceException e) {
87  			final String msg = e.getResponse().getEntity(String.class);
88  			if (errorCode != e.getResponse().getStatus()) {
89  				Assert.fail("Unexpected error code and message [" + msg
90  						+ "]. Expected [" + errorCode + "], actual [" + e.getResponse().getStatus() + "]");
91  			}
92  //			Assert.assertEquals(errorCode, );
93  		} catch (RestClientException e) {
94  			Assert.assertTrue("Expected UniformInterfaceException cause, but was [" + e.getCause() + "]", e.getCause() instanceof UniformInterfaceException);
95  			Assert.assertEquals(errorCode, ((UniformInterfaceException) e.getCause()).getResponse().getStatus());
96  			if (message != null) {
97  				Assert.assertEquals(message, e.getMessage());
98  			}
99  		}
100 	}
101 
102 	public static void assertErrorCodeWithRegexp(int errorCode, String regExp, Runnable runnable) {
103 		try {
104 			runnable.run();
105 			Assert.fail(UniformInterfaceException.class + " exception expected");
106 		} catch (UniformInterfaceException e) {
107 			Assert.assertEquals(errorCode, e.getResponse().getStatus());
108 		} catch (RestClientException e) {
109 			Assert.assertTrue(e.getCause() instanceof UniformInterfaceException);
110 			Assert.assertEquals(errorCode, ((UniformInterfaceException) e.getCause()).getResponse().getStatus());
111 			Assert.assertTrue("'" + e.getMessage() + "' does not match regexp '" + regExp + "'", e.getMessage().matches(regExp));
112 		}
113 	}
114 
115 
116 	public static String getLastPathSegment(URI uri) {
117 		final String path = uri.getPath();
118 		final int index = path.lastIndexOf('/');
119 		if (index == -1) {
120 			return path;
121 		}
122 		if (index == path.length()) {
123 			return "";
124 		}
125 		return path.substring(index + 1);
126 	}
127 
128 	public static <E> void assertEqualsSymmetrical(E a, E b) {
129 		Assert.assertEquals(a, b);
130 		Assert.assertEquals(b, a);
131 	}
132 
133 	public static <E> void assertNotEquals(E a, E b) {
134 		if (a == null) {
135 			Assert.assertFalse("[" + a + "] not equals [" + b + "]", b.equals(a));
136 		} else if (b == null) {
137 			Assert.assertFalse("[" + a + "] not equals [" + b + "]", a.equals(b));
138 		} else if (a.equals(b) || b.equals(a)) {
139 			Assert.fail("[" + a + "] not equals [" + b + "]");
140 		}
141 	}
142 
143 	public static <T extends NamedEntity> T findEntityByName(Iterable<T> entities, final String name) {
144 		return Iterables.find(entities, HasNamePredicate.forName(name));
145 	}
146 
147 	@Nullable
148 	public static Transition getTransitionByName(Iterable<Transition> transitions, String transitionName) {
149 		Transition transitionFound = null;
150 		for (Transition transition : transitions) {
151 			if (transition.getName().equals(transitionName)) {
152 				transitionFound = transition;
153 				break;
154 			}
155 		}
156 		return transitionFound;
157 	}
158 
159 	public static class HasNamePredicate<T extends NamedEntity> implements Predicate<T>{
160 	
161 		private final String name;
162 
163 		public static <K extends NamedEntity> HasNamePredicate<K> forName(String name) {
164 			return new HasNamePredicate<K>(name);
165 		}
166 
167 		private HasNamePredicate(String name) {
168 			this.name = name;
169 		}
170 
171 		@Override
172 		public boolean apply(T input) {
173 			return name.equals(input.getName());
174 		}
175 	}
176 }