Elffuss BraidHub

kikocis/java-driver public

Add tests for error messages.
Changeset0518208fb53cb7c310d6810a2053ffa1b45c0cf36fea1c7cad38827c0dcffbfd
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-05-31 18:32 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2016-07-22 09:47 -07:00
Parentsc52f9bfb9370

Browse the files at this changeset

3 files changed

modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationChecks.java +20 −30
@@ -20,7 +20,10 @@
2020 import com.datastax.driver.mapping.annotations.Table;
2121
2222 import java.lang.annotation.Annotation;
23-import java.util.*;
23+import java.util.Collection;
24+import java.util.Collections;
25+import java.util.HashSet;
26+import java.util.List;
2427
2528 /**
2629 * Various checks on mapping annotations.
@@ -37,8 +40,8 @@
3740 static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) {
3841 T instance = annotatedClass.getAnnotation(annotation);
3942 if (instance == null)
40- throw new IllegalArgumentException(String.format("@%s annotation was not found on type %s",
41- annotation.getSimpleName(), annotatedClass.getName()));
43+ throw new IllegalArgumentException(String.format("@%s annotation was not found on %s",
44+ annotation.getSimpleName(), annotatedClass));
4245
4346 // Check that no other mapping annotations are present
4447 validateAnnotations(annotatedClass, annotation);
@@ -49,75 +52,62 @@
4952 @SuppressWarnings("unchecked")
5053 private static void validateAnnotations(Class<?> clazz, Class<? extends Annotation> allowed) {
5154 @SuppressWarnings("unchecked")
52- Set<Annotation> classAnnotations = new HashSet<Annotation>();
55+ Collection<Annotation> classAnnotations = new HashSet<Annotation>();
5356 Collections.addAll(classAnnotations, clazz.getAnnotations());
54- Class<? extends Annotation> invalid = validateAnnotations(classAnnotations, allowed);
57+ Class<? extends Annotation> invalid = validateAnnotations(classAnnotations, Collections.singleton(allowed));
5558 if (invalid != null)
56- throw new IllegalArgumentException(String.format("Cannot have both @%s and @%s on type %s",
59+ throw new IllegalArgumentException(String.format("Cannot have both @%s and @%s on %s",
5760 allowed.getSimpleName(), invalid.getSimpleName(),
58- clazz.getName()));
61+ clazz));
5962 }
6063
6164 /**
6265 * Checks that a field is only annotated with the given mapping annotations, and that its "frozen" annotations are valid.
6366 */
64- static void validateAnnotations(PropertyMapper property, Class<? extends Annotation>... allowed) {
67+ static void validateAnnotations(PropertyMapper property, Collection<? extends Class<? extends Annotation>> allowed) {
6568 Class<? extends Annotation> invalid = validateAnnotations(property.getAnnotations(), allowed);
66- if (invalid != null)
67- throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on property %s",
69+ if (invalid != null) {
70+ throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on property '%s'",
6871 invalid.getSimpleName(),
6972 property));
73+ }
7074 checkValidPrimaryKey(property);
7175 checkValidComputed(property);
7276 }
7377
7478 // Returns the offending annotation if there is one
75- private static Class<? extends Annotation> validateAnnotations(Collection<Annotation> annotations, Class<? extends Annotation>... allowed) {
79+ private static Class<? extends Annotation> validateAnnotations(Collection<Annotation> annotations, Collection<? extends Class<? extends Annotation>> allowed) {
7680 for (Annotation annotation : annotations) {
7781 Class<? extends Annotation> actual = annotation.annotationType();
78- if (actual.getPackage().equals(MAPPING_PACKAGE) && !contains(allowed, actual))
82+ if (actual.getPackage().equals(MAPPING_PACKAGE) && !allowed.contains(actual))
7983 return actual;
8084 }
8185 return null;
8286 }
8387
84- private static boolean contains(Object[] array, Object target) {
85- for (Object element : array)
86- if (element.equals(target))
87- return true;
88- return false;
89- }
90-
9188 private static void checkValidPrimaryKey(PropertyMapper property) {
9289 if (property.isPartitionKey() && property.isClusteringColumn())
93- throw new IllegalArgumentException("Property " + property + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
90+ throw new IllegalArgumentException(String.format("Property '%s' cannot be annotated with both @PartitionKey and @ClusteringColumn", property));
9491 }
9592
9693 private static void checkValidComputed(PropertyMapper property) {
9794 if (property.isComputed()) {
9895 Computed computed = property.annotation(Computed.class);
9996 if (computed.value().isEmpty()) {
100- throw new IllegalArgumentException(String.format("Property %s: attribute 'value' of annotation @Computed is mandatory for computed properties", property));
97+ throw new IllegalArgumentException(String.format("Property '%s': attribute 'value' of annotation @Computed is mandatory for computed properties", property));
10198 }
10299 if (property.hasAnnotation(Column.class)) {
103- throw new IllegalArgumentException("Cannot use @Column and @Computed on the same property");
100+ throw new IllegalArgumentException(String.format("Property '%s' cannot be annotated with both @Column and @Computed", property));
104101 }
105102 }
106103 }
107104
108- static void validatePrimaryKeyOnUDT(PropertyMapper property) {
109- if (property.isPartitionKey())
110- throw new IllegalArgumentException("Annotation @PartitionKey is not allowed in a class annotated by @UDT");
111- else if (property.isClusteringColumn())
112- throw new IllegalArgumentException("Annotation @ClusteringColumn is not allowed in a class annotated by @UDT");
113- }
114-
115105 static void validateOrder(List<PropertyMapper> properties, String annotation) {
116106 for (int i = 0; i < properties.size(); i++) {
117107 PropertyMapper property = properties.get(i);
118108 int pos = property.getPosition();
119109 if (pos != i)
120- throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of property %s, was expecting %d",
110+ throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of property '%s', was expecting %d",
121111 pos, annotation, property, i));
122112 }
123113 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +25 −8
@@ -21,7 +21,9 @@
2121 import com.datastax.driver.core.UserType;
2222 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
2323 import com.datastax.driver.mapping.annotations.*;
24+import com.google.common.annotations.VisibleForTesting;
2425 import com.google.common.base.Strings;
26+import com.google.common.collect.ImmutableSet;
2527 import com.google.common.reflect.TypeToken;
2628
2729 import java.beans.PropertyDescriptor;
@@ -43,6 +45,25 @@
4345 @SuppressWarnings("unchecked")
4446 class AnnotationParser {
4547
48+ @VisibleForTesting
49+ static final Set<Class<? extends Annotation>> VALID_PROPERTY_ANNOTATIONS = ImmutableSet.of(
50+ Column.class,
51+ ClusteringColumn.class,
52+ Frozen.class,
53+ FrozenKey.class,
54+ FrozenValue.class,
55+ PartitionKey.class,
56+ Transient.class,
57+ Computed.class);
58+
59+ @VisibleForTesting
60+ static final Set<Class<? extends Annotation>> VALID_FIELD_ANNOTATIONS = ImmutableSet.of(
61+ Field.class,
62+ Frozen.class,
63+ FrozenKey.class,
64+ FrozenValue.class,
65+ Transient.class);
66+
4667 private static final Comparator<PropertyMapper> POSITION_COMPARATOR = new Comparator<PropertyMapper>() {
4768 @Override
4869 public int compare(PropertyMapper o1, PropertyMapper o2) {
@@ -99,9 +120,7 @@
99120 if (mappingManager.isCassandraV1 && propertyMapper.isComputed())
100121 throw new UnsupportedOperationException("Computed properties are not supported with native protocol v1");
101122
102- AnnotationChecks.validateAnnotations(propertyMapper,
103- Column.class, ClusteringColumn.class, Frozen.class, FrozenKey.class,
104- FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
123+ AnnotationChecks.validateAnnotations(propertyMapper, VALID_PROPERTY_ANNOTATIONS);
105124
106125 if (propertyMapper.isTransient())
107126 continue;
@@ -164,9 +183,7 @@
164183
165184 PropertyMapper propertyMapper = new PropertyMapper(propertyName, null, field, property);
166185
167- AnnotationChecks.validateAnnotations(propertyMapper,
168- Field.class, Frozen.class, FrozenKey.class,
169- FrozenValue.class, Transient.class);
186+ AnnotationChecks.validateAnnotations(propertyMapper, VALID_FIELD_ANNOTATIONS);
170187
171188 if (propertyMapper.isTransient())
172189 continue;
@@ -175,15 +192,15 @@
175192 throw new IllegalArgumentException(String.format("Field %s does not exist in type %s.%s",
176193 propertyMapper.columnName, ksName, userType.getTypeName()));
177194
178- AnnotationChecks.validatePrimaryKeyOnUDT(propertyMapper);
179195 propertyMappers.put(propertyMapper.columnName, propertyMapper);
180196 }
197+
181198 return new MappedUDTCodec<T>(userType, udtClass, propertyMappers, mappingManager);
182199 }
183200
184201 static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, MappingManager mappingManager) {
185202 if (!accClass.isInterface())
186- throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
203+ throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces, got " + accClass);
187204
188205 AnnotationChecks.getTypeAnnotation(Accessor.class, accClass);
189206
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidAnnotationsTest.java +256 −0
@@ -0,0 +1,256 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
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+package com.datastax.driver.mapping;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.mapping.annotations.*;
20+import org.testng.annotations.BeforeClass;
21+import org.testng.annotations.Test;
22+
23+import static org.mockito.Mockito.*;
24+
25+@SuppressWarnings({"unused", "WeakerAccess"})
26+public class MapperInvalidAnnotationsTest {
27+
28+ MappingManager mappingManager;
29+
30+ @BeforeClass(groups = "unit")
31+ public void setup() {
32+ mappingManager = mock(MappingManager.class);
33+ Session session = mock(Session.class);
34+ when(mappingManager.getSession()).thenReturn(session);
35+ Cluster cluster = mock(Cluster.class);
36+ when(session.getCluster()).thenReturn(cluster);
37+ Metadata metadata = mock(Metadata.class);
38+ when(cluster.getMetadata()).thenReturn(metadata);
39+ KeyspaceMetadata keyspace = mock(KeyspaceMetadata.class);
40+ when(metadata.getKeyspace(anyString())).thenReturn(keyspace);
41+
42+ UserType userType = mock(UserType.class);
43+ when(keyspace.getUserType(anyString())).thenReturn(userType);
44+ when(userType.contains(anyString())).thenReturn(true);
45+
46+ TableMetadata table = mock(TableMetadata.class);
47+ when(keyspace.getTable(anyString())).thenReturn(table);
48+ ColumnMetadata column = mock(ColumnMetadata.class);
49+ when(table.getColumn(anyString())).thenReturn(column);
50+ }
51+
52+ static class Invalid1 {
53+ }
54+
55+ @Table(name = "foo")
56+ @UDT(name = "foo")
57+ static class Invalid2 {
58+ }
59+
60+ @Table(name = "foo")
61+ @Accessor
62+ static class Invalid3 {
63+ }
64+
65+ @UDT(name = "foo")
66+ @Accessor
67+ static class Invalid4 {
68+ }
69+
70+ interface Invalid5 {
71+ }
72+
73+ @Table(name = "foo")
74+ @Accessor
75+ interface Invalid6 {
76+ }
77+
78+ @UDT(name = "foo")
79+ @Accessor
80+ interface Invalid7 {
81+ }
82+
83+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
84+ expectedExceptionsMessageRegExp =
85+ "@Table annotation was not found on class " +
86+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid1")
87+ public void should_throw_IAE_when_Table_annotation_not_found_on_entity_class() throws Exception {
88+ AnnotationParser.parseEntity(Invalid1.class, mappingManager);
89+ }
90+
91+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
92+ expectedExceptionsMessageRegExp =
93+ "Cannot have both @Table and @UDT on class " +
94+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid2")
95+ public void should_throw_IAE_when_UDT_annotation_found_on_entity_class() throws Exception {
96+ AnnotationParser.parseEntity(Invalid2.class, mappingManager);
97+ }
98+
99+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
100+ expectedExceptionsMessageRegExp =
101+ "Cannot have both @Table and @Accessor on class " +
102+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid3")
103+ public void should_throw_IAE_when_Accessor_annotation_found_on_entity_class() throws Exception {
104+ AnnotationParser.parseEntity(Invalid3.class, mappingManager);
105+ }
106+
107+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
108+ expectedExceptionsMessageRegExp =
109+ "@UDT annotation was not found on class " +
110+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid1")
111+ public void should_throw_IAE_when_UDT_annotation_not_found_on_udt_class() throws Exception {
112+ AnnotationParser.parseUDT(Invalid1.class, mappingManager);
113+ }
114+
115+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
116+ expectedExceptionsMessageRegExp =
117+ "Cannot have both @UDT and @Table on class " +
118+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid2")
119+ public void should_throw_IAE_when_Table_annotation_found_on_udt_class() throws Exception {
120+ AnnotationParser.parseUDT(Invalid2.class, mappingManager);
121+ }
122+
123+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
124+ expectedExceptionsMessageRegExp =
125+ "Cannot have both @UDT and @Accessor on class " +
126+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid4")
127+ public void should_throw_IAE_when_Accessor_annotation_found_on_udt_class() throws Exception {
128+ AnnotationParser.parseUDT(Invalid4.class, mappingManager);
129+ }
130+
131+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
132+ expectedExceptionsMessageRegExp =
133+ "@Accessor annotation was not found on interface " +
134+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid5")
135+ public void should_throw_IAE_when_Accessor_annotation_not_found_on_accessor_class() throws Exception {
136+ AnnotationParser.parseAccessor(Invalid5.class, mappingManager);
137+ }
138+
139+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
140+ expectedExceptionsMessageRegExp =
141+ "Cannot have both @Accessor and @Table on interface " +
142+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid6")
143+ public void should_throw_IAE_when_Table_annotation_found_on_accessor_class() throws Exception {
144+ AnnotationParser.parseAccessor(Invalid6.class, mappingManager);
145+ }
146+
147+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
148+ expectedExceptionsMessageRegExp =
149+ "Cannot have both @Accessor and @UDT on interface " +
150+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid7")
151+ public void should_throw_IAE_when_UDT_annotation_found_on_accessor_class() throws Exception {
152+ AnnotationParser.parseAccessor(Invalid7.class, mappingManager);
153+ }
154+
155+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
156+ expectedExceptionsMessageRegExp =
157+ "@Accessor annotation is only allowed on interfaces, got class " +
158+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid4")
159+ public void should_throw_IAE_when_Accessor_annotation_found_on_concrete_class() throws Exception {
160+ AnnotationParser.parseAccessor(Invalid4.class, mappingManager);
161+ }
162+
163+ @Table(name = "foo", keyspace = "ks")
164+ static class Invalid8 {
165+ @Field
166+ int invalid;
167+ }
168+
169+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
170+ expectedExceptionsMessageRegExp =
171+ "Annotation @Field is not allowed on property 'invalid'")
172+ public void should_not_allow_Field_on_entity_class() throws Exception {
173+ AnnotationParser.parseEntity(Invalid8.class, mappingManager);
174+ }
175+
176+ @UDT(name = "foo", keyspace = "ks")
177+ static class Invalid9 {
178+
179+ int invalid;
180+
181+ @Column
182+ public int getInvalid() {
183+ return invalid;
184+ }
185+ }
186+
187+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
188+ expectedExceptionsMessageRegExp =
189+ "Annotation @Column is not allowed on property 'invalid'")
190+ public void should_not_allow_Column_on_udt_class() throws Exception {
191+ AnnotationParser.parseUDT(Invalid9.class, mappingManager);
192+ }
193+
194+ @Table(name = "foo", keyspace = "ks")
195+ static class Invalid10 {
196+
197+ @PartitionKey
198+ @ClusteringColumn
199+ int invalid;
200+
201+ }
202+
203+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
204+ expectedExceptionsMessageRegExp =
205+ "Property 'invalid' cannot be annotated with both @PartitionKey and @ClusteringColumn")
206+ public void should_not_allow_PartitionKey_and_ClusteringColumn_on_same_property() throws Exception {
207+ AnnotationParser.parseEntity(Invalid10.class, mappingManager);
208+ }
209+
210+ @Table(name = "foo", keyspace = "ks")
211+ static class Invalid11 {
212+
213+ @Computed("foo")
214+ @Column
215+ int invalid;
216+
217+ }
218+
219+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
220+ expectedExceptionsMessageRegExp =
221+ "Property 'invalid' cannot be annotated with both @Column and @Computed")
222+ public void should_not_allow_Computed_and_Column_on_same_property() throws Exception {
223+ AnnotationParser.parseEntity(Invalid11.class, mappingManager);
224+ }
225+
226+ @Table(name = "foo", keyspace = "ks")
227+ static class Invalid12 {
228+
229+ @Computed("")
230+ int invalid;
231+
232+ }
233+
234+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
235+ expectedExceptionsMessageRegExp =
236+ "Property 'invalid': attribute 'value' of annotation @Computed is mandatory for computed properties")
237+ public void should_not_allow_Computed_with_empty_value() throws Exception {
238+ AnnotationParser.parseEntity(Invalid12.class, mappingManager);
239+ }
240+
241+ @Table(name = "foo", keyspace = "ks")
242+ static class Invalid13 {
243+
244+ @PartitionKey(-1)
245+ int invalid;
246+
247+ }
248+
249+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
250+ expectedExceptionsMessageRegExp =
251+ "Invalid ordering value -1 for annotation @PartitionKey of property 'invalid', was expecting 0")
252+ public void should_not_allow_PartitionKey_with_wrong_order() throws Exception {
253+ AnnotationParser.parseEntity(Invalid13.class, mappingManager);
254+ }
255+
256+}