Skip to content

Commit

Permalink
added more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
bmatthias committed Nov 15, 2013
1 parent f69157b commit fc390fc
Show file tree
Hide file tree
Showing 18 changed files with 405 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 2,12 @@


import com.google.common.collect.Lists;
import com.tngtech.configbuilder.util.FieldValueTransformer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;

public class CollectionTransformer extends ITypeTransformer<Collection,ArrayList> {
public class CollectionTransformer extends TypeTransformer<Collection,ArrayList> {

@Override
public ArrayList transform(Collection argument) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 3,8 @@
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CommaSeparatedStringToStringCollectionTransformer extends ITypeTransformer<String, ArrayList<String>> {
public class CommaSeparatedStringToStringCollectionTransformer extends TypeTransformer<String, ArrayList<String>> {

@Override
public ArrayList<String> transform(String argument) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 4,7 @@

import java.util.Collection;

public class StringCollectionToCommaSeparatedStringTransformer extends ITypeTransformer<Collection<String>, String> {
public class StringCollectionToCommaSeparatedStringTransformer extends TypeTransformer<Collection<String>, String> {

@Override
public String transform(Collection<String> argument) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 6,7 @@
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;

public class StringOrPrimitiveToPrimitiveTransformer extends ITypeTransformer<Object,Object>{
public class StringOrPrimitiveToPrimitiveTransformer extends TypeTransformer<Object,Object> {

@Override
public Object transform(Object argument) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 3,7 @@
import java.nio.file.Path;
import java.nio.file.Paths;

public class StringToPathTransformer extends ITypeTransformer<String, Path>{
public class StringToPathTransformer extends TypeTransformer<String, Path> {
@Override
public Path transform(String argument) {
return Paths.get(argument);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 1,61 @@
package com.tngtech.configbuilder.annotation.typetransformer;

import com.tngtech.configbuilder.configuration.ErrorMessageSetup;
import com.tngtech.configbuilder.util.GenericsAndCastingHelper;
import com.tngtech.configbuilder.util.ConfigBuilderFactory;
import com.tngtech.configbuilder.util.FieldValueTransformer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;

/**
* Implementations of this interface transform an object into a different type of object
* @param <SourceClass> the type of the parameter before the transformation
* @param <TargetClass> return type
*/
public abstract class TypeTransformer<SourceClass, TargetClass> {

protected Type targetType;
protected FieldValueTransformer fieldValueTransformer;
protected GenericsAndCastingHelper genericsAndCastingHelper;
protected ErrorMessageSetup errorMessageSetup;
protected ArrayList<Class> availableTransformers;

public abstract TargetClass transform(SourceClass argument);

public void initialize(FieldValueTransformer fieldValueTransformer, ConfigBuilderFactory configBuilderFactory, Type targetType, ArrayList<Class> availableTransformers) {

this.targetType = targetType;
this.fieldValueTransformer = fieldValueTransformer;
this.genericsAndCastingHelper = configBuilderFactory.getInstance(GenericsAndCastingHelper.class);
this.errorMessageSetup = configBuilderFactory.getInstance(ErrorMessageSetup.class);
this.availableTransformers = availableTransformers;
}

public boolean isMatching(Class<?> sourceClass, Class<?> targetClass) {
Class<?> transformerSourceClass = getTransformerSourceClass();
Class<?> transformerTargetClass = getTransformerTargetClass();
if(transformerSourceClass.isAssignableFrom(sourceClass) && targetClass.isAssignableFrom(transformerTargetClass)) {
return true;
}
return false;
}

protected Class<?> getTransformerSourceClass() {
Type typeOfInterface = this.getClass().getGenericSuperclass();
Type[] genericTypes = ((ParameterizedType) typeOfInterface).getActualTypeArguments();
return genericsAndCastingHelper.castTypeToClass(genericTypes[0]);
}

protected Class<?> getTransformerTargetClass() {
Type typeOfInterface = this.getClass().getGenericSuperclass();
Type[] genericTypes = ((ParameterizedType) typeOfInterface).getActualTypeArguments();
return genericsAndCastingHelper.castTypeToClass(genericTypes[1]);
}


public void setGenericsAndCastingHelper(GenericsAndCastingHelper genericsAndCastingHelper) {
this.genericsAndCastingHelper = genericsAndCastingHelper;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 6,7 @@
import java.lang.annotation.Target;

/**
* This annotation uses a lists of classes that implements the {@link ITypeTransformer} interface in order to transform the type of the annotated field.<br>
* This annotation uses a lists of classes that implements the {@link TypeTransformer} interface in order to transform the type of the annotated field.<br>
* <b>Usage:</b> <code>@TypeTransformer({AClassThatImplementsITypeTransformer.class, AnotherClassThatImplementsITypeTransofrmer})</code>
*/
@Target(ElementType.FIELD)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 69,26 @@ public <K> K getInstance(Class<K> clazz) {
}
}

//TODO: Make this work if config class has no default constructor & better exception
//TODO: exception message
public <K> K createInstance(Class<K> clazz) {
try {
return clazz.newInstance();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
Class superClass = clazz.getDeclaringClass();
try {
Object superInstance = superClass.newInstance();
Constructor<K> constructor = clazz.getConstructor(superClass);
return constructor.newInstance(superInstance);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
return createInstanceOfInnerClass(clazz);
}
}

//TODO: exception message
private <K> K createInstanceOfInnerClass(Class<K> clazz) {
Class superClass = clazz.getDeclaringClass();
try {
Object superInstance = superClass.newInstance();
Constructor<K> constructor = clazz.getConstructor(superClass);
return constructor.newInstance(superInstance);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 20,11 @@ public class FieldValueTransformer {
private final GenericsAndCastingHelper genericsAndCastingHelper;

private final ArrayList<Class> defaultTransformers = Lists.newArrayList(new Class[]{
StringOrPrimitiveToPrimitiveTransformer.class,
CommaSeparatedStringToStringCollectionTransformer.class,
StringCollectionToCommaSeparatedStringTransformer.class,
StringToPathTransformer.class,
CollectionTransformer.class,
StringOrPrimitiveToPrimitiveTransformer.class});
StringCollectionToCommaSeparatedStringTransformer.class,
StringToPathTransformer.class});

public FieldValueTransformer(ConfigBuilderFactory configBuilderFactory) {
this.configBuilderFactory = configBuilderFactory;
Expand All @@ -46,15 46,15 @@ public Object performNecessaryTransformations(Object sourceValue, Type targetTyp

log.info(String.format("Searching for a transformer from %s to %s", sourceClass.toString(), targetClass.toString()));

ITypeTransformer<Object, ?> transformer = findApplicableTransformer(sourceClass, targetType, allTransformers);
TypeTransformer<Object, ?> transformer = findApplicableTransformer(sourceClass, targetType, allTransformers);
sourceValue = transformer.transform(sourceValue);
return performNecessaryTransformations(sourceValue, targetType, allTransformers);
}

private ITypeTransformer findApplicableTransformer(Class<?> sourceClass, Type targetType, ArrayList<Class> availableTransformerClasses) {
private TypeTransformer findApplicableTransformer(Class<?> sourceClass, Type targetType, ArrayList<Class> availableTransformerClasses) {
Class<?> targetClass = genericsAndCastingHelper.getWrapperClassForPrimitive(genericsAndCastingHelper.castTypeToClass(targetType));
for(Class<ITypeTransformer> clazz: availableTransformerClasses) {
ITypeTransformer transformer = configBuilderFactory.getInstance(clazz);
for(Class<TypeTransformer> clazz: availableTransformerClasses) {
TypeTransformer transformer = configBuilderFactory.getInstance(clazz);
transformer.setGenericsAndCastingHelper(genericsAndCastingHelper);
if(transformer.isMatching(sourceClass, targetClass)) {
transformer.initialize(this, configBuilderFactory, targetType, availableTransformerClasses);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 22,11 @@ public GenericsAndCastingHelper() {
primitiveToWrapperMapping.put(double.class, Double.class);
}

public Class<?> getWrapperClassForPrimitive(Class primitiveClass) {
return primitiveToWrapperMapping.get(primitiveClass) == null? primitiveClass : primitiveToWrapperMapping.get(primitiveClass);
public Class getWrapperClassForPrimitive(Class clazz) {
return primitiveToWrapperMapping.get(clazz) == null? clazz : primitiveToWrapperMapping.get(clazz);
}

public Class<?> castTypeToClass(Type object) {
public Class castTypeToClass(Type object) {
if(object.getClass().equals(Class.class)) {
return (Class<?>) object;
} else {
Expand Down Expand Up @@ -56,7 56,7 @@ else if(Collection.class.isAssignableFrom((Class<?>)((ParameterizedType)targetTy
return false;
}
}
return ((Class<?>)targetType).isAssignableFrom(sourceClass);
return (castTypeToClass(targetType)).isAssignableFrom(sourceClass);
}

public boolean isPrimitiveOrWrapper(Class targetClass) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 9,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand All @@ -29,11 30,13 @@ public void setUp() {
@Parameterized.Parameters
public static Collection configs() {
TestConfig testConfig = new TestConfig();
testConfig.setHelloWorld("Hello, World!");
testConfig.setSomeString("Hello, World!");
testConfig.setSomeNumber(3);
testConfig.setBoolean(true);
testConfig.setStringCollection(Lists.newArrayList("one entry"));
testConfig.setEnvironmentVariable(System.getenv("PATH"));
testConfig.setStringCollection(Lists.newArrayList("first entry","second entry"));
testConfig.setIntegerList(Lists.newArrayList(1,2,3,4,5));
testConfig.setPathCollection(Lists.newArrayList(Paths.get("/etc"),Paths.get("/usr")));
testConfig.setHomeDir(Paths.get(System.getenv("HOME")));
testConfig.setSystemProperty(System.getProperty("user.language"));

return Arrays.asList(new Object[][]{{TestConfig.class, testConfig}});
Expand All @@ -47,7 50,7 @@ public ConfigBuilderIntegrationTest(Class configClass, Object configInstance) {
@Test
public void testConfigBuilderWithParameters() {
ConfigBuilder configBuilder = new ConfigBuilder(configClass);
String[] args = new String[]{"-u", "--collection", "one entry"};
String[] args = new String[]{"-u", "--collection", "first entry,second entry"};
Object result = configBuilder.withCommandLineArgs(args).build();
assertReflectionEquals(configInstance, result);
}
Expand All @@ -62,28 65,30 @@ public void testConfigBuilderWithConstructorArgument() {
@Test
public void testMerge() {
ArrayList<String> arrayList = Lists.newArrayList("collection", "two");
String systemPath = System.getenv("PATH");
String home = System.getenv("HOME");
String userLanguage = System.getProperty("user.language");

TestConfig originalTestConfig = new TestConfig();
originalTestConfig.setHelloWorld("astringwithoutspaces");
originalTestConfig.setSomeString("astringwithoutspaces");
originalTestConfig.setSomeNumber(3);
originalTestConfig.setBoolean(true);
originalTestConfig.setStringCollection(Lists.newArrayList("collection"));
originalTestConfig.setEnvironmentVariable(systemPath);
originalTestConfig.setHomeDir(Paths.get(home));
originalTestConfig.setSystemProperty(userLanguage);

TestConfig overwritingTestConfig = new TestConfig();
overwritingTestConfig.setHelloWorld("Hello World!");
overwritingTestConfig.setSomeString("Hello World!");
overwritingTestConfig.setBoolean(false);
overwritingTestConfig.setStringCollection(arrayList);

TestConfig expectedTestConfig = new TestConfig();
expectedTestConfig.setHelloWorld("Hello World!");
expectedTestConfig.setSomeString("Hello World!");
expectedTestConfig.setSomeNumber(3);
expectedTestConfig.setBoolean(true); // primitives will not be overwritten
expectedTestConfig.setStringCollection(arrayList);
expectedTestConfig.setEnvironmentVariable(systemPath);
expectedTestConfig.setIntegerList(Lists.newArrayList(1,2,3,4,5));
expectedTestConfig.setPathCollection(Lists.newArrayList(Paths.get("/etc"),Paths.get("/usr")));
expectedTestConfig.setHomeDir(Paths.get(home));
expectedTestConfig.setSystemProperty(userLanguage);


Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 1,62 @@
package com.tngtech.configbuilder.annotation.typetransformer;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.tngtech.configbuilder.configuration.ErrorMessageSetup;
import com.tngtech.configbuilder.util.ConfigBuilderFactory;
import com.tngtech.configbuilder.util.FieldValueTransformer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class CollectionTransformerTest {

private CollectionTransformer collectionTransformer;

@Mock
private ParameterizedType type;
@Mock
private FieldValueTransformer fieldValueTransformer;
@Mock
private ConfigBuilderFactory configBuilderFactory;
@Mock
private ErrorMessageSetup errorMessageSetup;

@Before
public void setUp() throws Exception {
when(configBuilderFactory.getInstance(ErrorMessageSetup.class)).thenReturn(errorMessageSetup);

collectionTransformer = new CollectionTransformer();
collectionTransformer.initialize(fieldValueTransformer, configBuilderFactory, type, Lists.newArrayList(new Class[]{StringOrPrimitiveToPrimitiveTransformer.class}));
}

@Test
public void testTransform() throws Exception {

Set<Integer> input = Sets.newHashSet(1,2,3);
when(type.getActualTypeArguments()).thenReturn(new Class[]{Double.class});
when(fieldValueTransformer.performNecessaryTransformations(1, Double.class, Lists.newArrayList(new Class[]{StringOrPrimitiveToPrimitiveTransformer.class}))).thenReturn(1.0);
when(fieldValueTransformer.performNecessaryTransformations(2, Double.class, Lists.newArrayList(new Class[]{StringOrPrimitiveToPrimitiveTransformer.class}))).thenReturn(2.0);
when(fieldValueTransformer.performNecessaryTransformations(3, Double.class, Lists.newArrayList(new Class[]{StringOrPrimitiveToPrimitiveTransformer.class}))).thenReturn(3.0);
assertEquals(Lists.newArrayList(1.0,2.0,3.0), collectionTransformer.transform(input));
}

@Test
public void testIsMatching() throws Exception {

assertTrue(collectionTransformer.isMatching(Collection.class, ArrayList.class));
assertFalse(collectionTransformer.isMatching(Collection.class, Double.class));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 2,26 @@

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import java.nio.file.Paths;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
public class StringToPathTransformerTest {

private StringToPathTransformer stringToPathTransformer;

@Before
public void setUp() throws Exception {

stringToPathTransformer = new StringToPathTransformer();
}

@Test
public void testTransform() throws Exception {

assertEquals(Paths.get("/usr"), stringToPathTransformer.transform("/usr"));
}

@Test
Expand Down
Loading

0 comments on commit fc390fc

Please sign in to comment.