From 22615b76bda9eeef51069548ba2ce6df6dfbb58f Mon Sep 17 00:00:00 2001 From: William Lieurance Date: Sat, 24 Feb 2018 23:19:18 -0600 Subject: [PATCH] TAMAYA-288: Additional test coverage Things that this PR does * Significant increase in test coverage, especially mutation coverage ** API from 57% to 92% ** Core from 38% to 82% ** SPI-Support from ??% (mutation coverage disabled) to 86% * Tests now succeed with OpenJDK, Hotspot, and OpenJ9. * Generated a series of additional bug tickets. :-) What this does not do: * Touch any implementation code. This is only tests. * Reduce code duplication, especially between API/Core and SPI-Support. * Have a great answer for OSGI testing. It ends up being a pile of mocks. --- .gitignore | 3 +- .../tamaya/ConfigurationProviderTest.java | 103 +++ .../org/apache/tamaya/ConfigurationTest.java | 45 +- .../org/apache/tamaya/TestConfiguration.java | 133 ++-- .../tamaya/TestConfigurationProvider.java | 29 +- .../org/apache/tamaya/TypeLiteralTest.java | 67 +- .../spi/ConfigurationProviderSpiTest.java | 58 ++ .../spi/PropertySourceProviderTest.java | 35 + .../apache/tamaya/spi/PropertySourceTest.java | 71 ++ .../tamaya/spi/PropertyValueBuilderTest.java | 59 +- .../apache/tamaya/core/OSGIActivatorTest.java | 81 +++ .../CoreConfigurationBuilderTest.java | 36 +- .../tamaya/core/internal/MockBundle.java | 225 ++++++ .../core/internal/MockBundleContext.java | 202 ++++++ .../internal/OSGIServiceComparatorTest.java | 114 +++ .../core/internal/OSGIServiceContextTest.java | 129 ++++ .../core/internal/OSGIServiceLoaderTest.java | 114 +++ .../converters/BigDecimalConverterTest.java | 6 + .../converters/BigIntegerConverterTest.java | 161 +++++ .../converters/BooleanConverterTest.java | 36 + .../converters/ByteConverterTest.java | 32 + .../converters/CharConverterTest.java | 75 +- .../converters/ClassConverterTest.java | 15 + .../internal/converters/ConvertQueryTest.java | 80 +++ .../ConverterTestsPropertySource.java | 62 +- .../converters/CurrencyConverterTest.java | 60 +- .../converters/DoubleConverterTest.java | 51 +- .../converters/DurationConverterTest.java | 16 + .../converters/FileConverterTest.java | 58 ++ .../converters/FloatConverterTest.java | 51 +- .../converters/InstantConverterTest.java | 16 + .../converters/IntegerConverterTest.java | 26 + .../converters/LocalDateConverterTest.java | 15 + .../LocalDateTimeConverterTest.java | 15 + .../converters/LocalTimeConverterTest.java | 15 + .../converters/LongConverterTest.java | 26 + .../converters/NumberConverterTest.java | 78 +- .../OffsetDateTimeConverterTest.java | 16 + .../converters/OffsetTimeConverterTest.java | 18 +- .../converters/OptionalConverterTest.java | 43 +- .../converters/PathConverterTest.java | 33 +- .../converters/ShortConverterTest.java | 27 + .../converters/SupplierConverterTest.java | 84 +++ .../internal/converters/URIConverterTest.java | 27 + .../internal/converters/URLConverterTest.java | 25 + .../src/test/resources/mockbundle.service | 18 + code/spi-support/pom.xml | 14 - .../BuildablePropertySourceProviderTest.java | 26 +- .../BuildablePropertySourceTest.java | 63 +- .../DefaultConfigValueEvaluatorTest.java | 61 ++ .../DefaultConfigurationBuilderTest.java | 302 ++++++-- ...efaultConfigurationContextBuilderTest.java | 675 ++++++++++++++++++ .../DefaultConfigurationContextTest.java | 59 ++ .../spisupport/DefaultConfigurationTest.java | 177 ++--- .../tamaya/spisupport/EnumConverterTest.java | 60 +- .../spisupport/IntegerTestConverter.java | 41 ++ .../MockedConfigurationContext.java | 96 +++ .../spisupport/MockedPropertyFilter.java | 39 + .../spisupport/MockedPropertySource.java | 83 +++ .../PropertyConverterManagerTest.java | 60 ++ .../tamaya/spisupport/ReflectionUtilTest.java | 55 ++ .../spisupport/RegexPropertyFilterTest.java | 15 + .../BasePropertySourceTest.java | 47 +- .../propertysource/CLIPropertySourceTest.java | 84 ++- .../EnvironmentPropertySourceTest.java | 93 ++- .../JavaConfigurationProviderTest.java | 47 +- .../PropertiesResourcePropertySourceTest.java | 82 +++ .../SimplePropertySourceTest.java | 109 ++- .../SystemPropertySourceTest.java | 75 +- .../WrappedPropertySourceTest.java | 168 +++++ .../org.apache.tamaya.spi.PropertyConverter | 3 +- .../org.apache.tamaya.spi.PropertyFilter | 19 + .../org.apache.tamaya.spi.PropertySource | 19 + 73 files changed, 4859 insertions(+), 402 deletions(-) create mode 100644 code/api/src/test/java/org/apache/tamaya/ConfigurationProviderTest.java create mode 100644 code/api/src/test/java/org/apache/tamaya/spi/ConfigurationProviderSpiTest.java create mode 100644 code/api/src/test/java/org/apache/tamaya/spi/PropertySourceProviderTest.java create mode 100644 code/api/src/test/java/org/apache/tamaya/spi/PropertySourceTest.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/OSGIActivatorTest.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/MockBundle.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/MockBundleContext.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceComparatorTest.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceContextTest.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceLoaderTest.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/converters/BigIntegerConverterTest.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/converters/ConvertQueryTest.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/converters/FileConverterTest.java create mode 100644 code/core/src/test/java/org/apache/tamaya/core/internal/converters/SupplierConverterTest.java create mode 100644 code/core/src/test/resources/mockbundle.service create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigValueEvaluatorTest.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationContextBuilderTest.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationContextTest.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/IntegerTestConverter.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedConfigurationContext.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedPropertyFilter.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedPropertySource.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/ReflectionUtilTest.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/PropertiesResourcePropertySourceTest.java create mode 100644 code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySourceTest.java create mode 100644 code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter create mode 100644 code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource diff --git a/.gitignore b/.gitignore index 274ebae33..5a53be52b 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ modules/integration/commons-config/commons-configuration.iml examples/simple-propertysource/tamaya-example-simple-propertysource.iml **/*.checkstyle **/*.fbExcludeFilterFile - +nbproject +nb-configuration.xml diff --git a/code/api/src/test/java/org/apache/tamaya/ConfigurationProviderTest.java b/code/api/src/test/java/org/apache/tamaya/ConfigurationProviderTest.java new file mode 100644 index 000000000..e58806e06 --- /dev/null +++ b/code/api/src/test/java/org/apache/tamaya/ConfigurationProviderTest.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya; + +import org.apache.tamaya.spi.ConfigurationBuilder; +import org.apache.tamaya.spi.ConfigurationContext; +import org.apache.tamaya.spi.ConfigurationContextBuilder; +import org.junit.Test; +import static org.junit.Assert.*; +import org.mockito.Mockito; + +/** + * + * Test the {@link ConfigurationProivder} class. The tests end up being tests of + * the default methods in the {@link ConfigurationProivder} interface as they + * pass through to the {@link TestConfigurationProvider} mocked object. + */ +public class ConfigurationProviderTest { + + + /** + * Test of createConfiguration method, of class ConfigurationProvider. + */ + @Test + public void testCreateConfiguration() { + Configuration result = ConfigurationProvider.createConfiguration(ConfigurationProvider.getConfiguration().getContext()); + assertNotNull(result); + } + + /** + * Test of getConfigurationContext and setConfigurationContext method, of + * class ConfigurationProvider. + */ + @Test + public void testGetSetConfigurationContext() { + ConfigurationContext currentContext = ConfigurationProvider.getConfigurationContext(); + assertTrue(currentContext instanceof ConfigurationContext); + ConfigurationContext newContext = Mockito.mock(ConfigurationContext.class); + try{ + ConfigurationProvider.setConfigurationContext(newContext); + assertEquals(newContext, ConfigurationProvider.getConfigurationContext()); + }finally{ + ConfigurationProvider.setConfigurationContext(currentContext); + } + assertEquals(currentContext, ConfigurationProvider.getConfigurationContext()); + } + + /** + * Test of getConfiguration method, of class ConfigurationProvider. + */ + @Test + public void testGetSetConfiguration() { + Configuration currentConfig = ConfigurationProvider.getConfiguration(); + assertTrue(currentConfig instanceof Configuration); + Configuration newConfig = Mockito.mock(Configuration.class); + try{ + ConfigurationProvider.setConfiguration(newConfig); + assertEquals(newConfig, ConfigurationProvider.getConfiguration()); + }finally{ + ConfigurationProvider.setConfiguration(currentConfig); + } + assertEquals(currentConfig, ConfigurationProvider.getConfiguration()); + } + + /** + * Test of getConfigurationBuilder method, of class ConfigurationProvider. + */ + @Test + public void testGetConfigurationBuilder() { + ConfigurationBuilder result = ConfigurationProvider.getConfigurationBuilder(); + assertTrue(result instanceof ConfigurationBuilder); + } + + /** + * Test of getConfigurationContextBuilder method, of class ConfigurationProvider. + */ + @Test + public void testGetConfigurationContextBuilder() { + ConfigurationContextBuilder result = ConfigurationProvider.getConfigurationContextBuilder(); + assertTrue(result instanceof ConfigurationContextBuilder); + } + + @Test + public void testConstructorFails(){ + assertTrue(ConfigurationProvider.class.getConstructors().length == 0); + } +} diff --git a/code/api/src/test/java/org/apache/tamaya/ConfigurationTest.java b/code/api/src/test/java/org/apache/tamaya/ConfigurationTest.java index ecbb75ce3..26e205855 100644 --- a/code/api/src/test/java/org/apache/tamaya/ConfigurationTest.java +++ b/code/api/src/test/java/org/apache/tamaya/ConfigurationTest.java @@ -22,8 +22,10 @@ import static org.junit.Assert.*; /** - * Test class that tests the default methods implemented on {@link org.apache.tamaya.Configuration}. The provided - * {@link org.apache.tamaya.TestConfiguration} is implemeted with maximal use of the default methods. + * Test class that tests the default methods implemented on + * {@link org.apache.tamaya.Configuration}. The provided + * {@link org.apache.tamaya.TestConfiguration} is implemented with maximal use of + * the default methods. */ public class ConfigurationTest { @@ -31,11 +33,12 @@ public class ConfigurationTest { public void testget() throws Exception { assertEquals(Boolean.TRUE, ConfigurationProvider.getConfiguration().get("booleanTrue", Boolean.class)); assertEquals(Boolean.FALSE, ConfigurationProvider.getConfiguration().get("booleanFalse", Boolean.class)); - assertEquals((int)Byte.MAX_VALUE, (int)ConfigurationProvider.getConfiguration().get("byte", Byte.class)); - assertEquals(Integer.MAX_VALUE, (int)ConfigurationProvider.getConfiguration().get("int", Integer.class)); - assertEquals(Long.MAX_VALUE, (long)ConfigurationProvider.getConfiguration().get("long", Long.class)); - assertEquals(Float.MAX_VALUE, (double)ConfigurationProvider.getConfiguration().get("float", Float.class), 0.0d); + assertEquals((int) Byte.MAX_VALUE, (int) ConfigurationProvider.getConfiguration().get("byte", Byte.class)); + assertEquals(Integer.MAX_VALUE, (int) ConfigurationProvider.getConfiguration().get("int", Integer.class)); + assertEquals(Long.MAX_VALUE, (long) ConfigurationProvider.getConfiguration().get("long", Long.class)); + assertEquals(Float.MAX_VALUE, (double) ConfigurationProvider.getConfiguration().get("float", Float.class), 0.0d); assertEquals(Double.MAX_VALUE, ConfigurationProvider.getConfiguration().get("double", Double.class), 0.0d); + assertEquals("aStringValue", ConfigurationProvider.getConfiguration().get("String")); } @Test @@ -47,17 +50,39 @@ public void testGetBoolean() throws Exception { @Test public void testGetInteger() throws Exception { - assertEquals(Integer.MAX_VALUE,(int) ConfigurationProvider.getConfiguration().get("int", Integer.class)); + assertEquals(Integer.MAX_VALUE, (int) ConfigurationProvider.getConfiguration().get("int", Integer.class)); } @Test public void testGetLong() throws Exception { - assertEquals(Long.MAX_VALUE,(long) ConfigurationProvider.getConfiguration().get("long", Long.class)); + assertEquals(Long.MAX_VALUE, (long) ConfigurationProvider.getConfiguration().get("long", Long.class)); } @Test public void testGetDouble() throws Exception { - assertEquals(Double.MAX_VALUE,ConfigurationProvider.getConfiguration().get("double", Double.class), 0.0d); + assertEquals(Double.MAX_VALUE, ConfigurationProvider.getConfiguration().get("double", Double.class), 0.0d); } -} \ No newline at end of file + @Test + public void testGetOrDefault() throws Exception { + assertEquals("StringIfThereWasNotAValueThere", ConfigurationProvider.getConfiguration().getOrDefault("nonexistant", "StringIfThereWasNotAValueThere")); + assertEquals("StringIfThereWasNotAValueThere", ConfigurationProvider.getConfiguration().getOrDefault("nonexistant", String.class, "StringIfThereWasNotAValueThere")); + } + + @Test + public void testToBuilder() throws Exception { + assertNotNull(ConfigurationProvider.getConfiguration().toBuilder()); + } + + @Test + public void testWith() throws Exception { + ConfigOperator noop = (Configuration config) -> config; + assertNotNull(ConfigurationProvider.getConfiguration().with(noop)); + } + + @Test + public void testQuery() throws Exception { + ConfigQuery stringQuery = (ConfigQuery) (Configuration config) -> config.get("String"); + assertEquals("aStringValue", ConfigurationProvider.getConfiguration().query(stringQuery)); + } +} diff --git a/code/api/src/test/java/org/apache/tamaya/TestConfiguration.java b/code/api/src/test/java/org/apache/tamaya/TestConfiguration.java index f50c1dca1..dd85a8d89 100644 --- a/code/api/src/test/java/org/apache/tamaya/TestConfiguration.java +++ b/code/api/src/test/java/org/apache/tamaya/TestConfiguration.java @@ -18,120 +18,97 @@ */ package org.apache.tamaya; - import org.apache.tamaya.spi.ConfigurationContext; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; +import org.mockito.Mockito; /** - * Test Configuration class, that is used to testdata the default methods provided by the API. + * Test Configuration class, that is used to testdata the default methods + * provided by the API. */ -public class TestConfiguration implements Configuration{ +public class TestConfiguration implements Configuration { + + private static final Map VALUES; - private static final Map VALUES; static { VALUES = new HashMap<>(); - VALUES.put("long", String.valueOf(Long.MAX_VALUE)); - VALUES.put("int", String.valueOf(Integer.MAX_VALUE)); - VALUES.put("double", String.valueOf(Double.MAX_VALUE)); - VALUES.put("float", String.valueOf(Float.MAX_VALUE)); - VALUES.put("short", String.valueOf(Short.MAX_VALUE)); - VALUES.put("byte", String.valueOf(Byte.MAX_VALUE)); - VALUES.put("booleanTrue", "true"); - VALUES.put("booleanFalse", "false"); + VALUES.put("long", Long.MAX_VALUE); + VALUES.put("int", Integer.MAX_VALUE); + VALUES.put("double", Double.MAX_VALUE); + VALUES.put("float", Float.MAX_VALUE); + VALUES.put("short", Short.MAX_VALUE); + VALUES.put("byte", Byte.MAX_VALUE); VALUES.put("String", "aStringValue"); } - @Override - public String get(String key) { - return VALUES.get(key); - } - - @Override - public String getOrDefault(String key, String defaultValue) { - String val = get(key); - if(val==null){ - return defaultValue; - } - return val; - } - - @Override - public T getOrDefault(String key, Class type, T defaultValue) { - T val = get(key, type); - if(val==null){ - return defaultValue; - } - return val; - } - @SuppressWarnings("unchecked") - @Override - public T get(String key, Class type) { - if(type.equals(Long.class)){ - return (T)(Object)Long.MAX_VALUE; - } - else if(type.equals(Integer.class)){ - return (T)(Object) Integer.MAX_VALUE; - } - else if(type.equals(Double.class)){ - return (T)(Object) Double.MAX_VALUE; - } - else if(type.equals(Float.class)){ - return (T)(Object) Float.MAX_VALUE; - } - else if(type.equals(Short.class)){ - return (T)(Object) Short.MAX_VALUE; - } - else if(type.equals(Byte.class)){ - return (T)(Object) Byte.MAX_VALUE; - } - else if(type.equals(Boolean.class)){ - if("booleanTrue".equals(key)) { - return (T)Boolean.TRUE; - } - else{ - return (T)Boolean.FALSE; + @Override + public T get(String key, TypeLiteral type) { + if (type.getRawType().equals(Long.class)) { + return (T) VALUES.get(key); + } else if (type.getRawType().equals(Integer.class)) { + return (T) VALUES.get(key); + } else if (type.getRawType().equals(Double.class)) { + return (T) VALUES.get(key); + } else if (type.getRawType().equals(Float.class)) { + return (T) VALUES.get(key); + } else if (type.getRawType().equals(Short.class)) { + return (T) VALUES.get(key); + } else if (type.getRawType().equals(Byte.class)) { + return (T) VALUES.get(key); + } else if (type.getRawType().equals(Boolean.class)) { + if ("booleanTrue".equals(key)) { + return (T) Boolean.TRUE; + } else { + return (T) Boolean.FALSE; } - } - else if(type.equals(String.class)){ - return (T)"aStringValue"; + } else if (type.getRawType().equals(String.class)) { + return (T) VALUES.get(key); } throw new ConfigException("No such property: " + key); } - @Override - public T get(String key, TypeLiteral type) { - throw new RuntimeException("Method not implemented yet."); - } - @Override public T getOrDefault(String key, TypeLiteral type, T defaultValue) { T val = get(key, type); - if(val==null){ + if (val == null) { return defaultValue; } return val; } @Override - public Configuration with(ConfigOperator operator) { - return null; + public ConfigurationContext getContext() { + return Mockito.mock(ConfigurationContext.class); } @Override - public T query(ConfigQuery query) { - throw new RuntimeException("Method not implemented yet."); + public Map getProperties() { + // run toString on each value of the (key, value) set in VALUES + return VALUES.entrySet().stream().collect( + Collectors.toMap( + Map.Entry::getKey, + e -> e.getValue().toString())); } @Override - public ConfigurationContext getContext() { - return null; + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof TestConfiguration)) { + return false; + } + TestConfiguration that = (TestConfiguration) o; + return that.getProperties().equals(this.getProperties()); } @Override - public Map getProperties() { - throw new RuntimeException("Method not implemented yet."); + public int hashCode() { + return VALUES.hashCode(); } + } diff --git a/code/api/src/test/java/org/apache/tamaya/TestConfigurationProvider.java b/code/api/src/test/java/org/apache/tamaya/TestConfigurationProvider.java index 1ccce3111..213612978 100644 --- a/code/api/src/test/java/org/apache/tamaya/TestConfigurationProvider.java +++ b/code/api/src/test/java/org/apache/tamaya/TestConfigurationProvider.java @@ -24,14 +24,17 @@ import org.apache.tamaya.spi.ConfigurationBuilder; import org.apache.tamaya.spi.ConfigurationContextBuilder; import org.apache.tamaya.spi.ConfigurationProviderSpi; +import org.mockito.Mockito; /** - * Test Configuration class, that is used to testdata the default methods provided by the API. + * Test Configuration class, that is used to testdata the default methods + * provided by the API. */ @Priority(-1) public class TestConfigurationProvider implements ConfigurationProviderSpi { - private static final Configuration config = new TestConfiguration(); + private Configuration config = new TestConfiguration(); + private ConfigurationContext context = Mockito.mock(ConfigurationContext.class); @Override public Configuration getConfiguration() { @@ -45,35 +48,31 @@ public Configuration createConfiguration(ConfigurationContext context) { @Override public ConfigurationContext getConfigurationContext() { - return config.getContext(); + return context; + } + + public ConfigurationContext getConfigurationContextFromInterface(){ + return ConfigurationProviderSpi.super.getConfigurationContext(); } @Override public void setConfigurationContext(ConfigurationContext context) { - throw new UnsupportedOperationException(); + this.context = context; } - @Override - public boolean isConfigurationContextSettable() { - return false; - } @Override public ConfigurationBuilder getConfigurationBuilder() { - return null; + return Mockito.mock(ConfigurationBuilder.class, Mockito.RETURNS_DEEP_STUBS); } @Override public ConfigurationContextBuilder getConfigurationContextBuilder() { - return null; + return Mockito.mock(ConfigurationContextBuilder.class); } @Override public void setConfiguration(Configuration config) { - } - - @Override - public boolean isConfigurationSettable() { - return false; + this.config = config; } } diff --git a/code/api/src/test/java/org/apache/tamaya/TypeLiteralTest.java b/code/api/src/test/java/org/apache/tamaya/TypeLiteralTest.java index 7435e08ce..65fe70628 100644 --- a/code/api/src/test/java/org/apache/tamaya/TypeLiteralTest.java +++ b/code/api/src/test/java/org/apache/tamaya/TypeLiteralTest.java @@ -18,6 +18,7 @@ */ package org.apache.tamaya; +import java.lang.reflect.Type; import static org.apache.tamaya.TypeLiteral.getGenericInterfaceTypeParameters; import static org.apache.tamaya.TypeLiteral.getTypeParameters; import static org.junit.Assert.assertEquals; @@ -25,8 +26,10 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.junit.Test; +import static org.junit.Assert.*; /** * Tests for the {@link TypeLiteral} class. @@ -34,21 +37,21 @@ @SuppressWarnings("serial") public class TypeLiteralTest { - @Test(expected = NullPointerException.class) + @Test(expected = NullPointerException.class) public void constructorRequiresNonNullParameter() { - new TypeLiteral>(null){}; + new TypeLiteral>(null) { }; } @Test - public void test_constrcutor(){ - TypeLiteral> listTypeLiteral = new TypeLiteral>(){}; + public void test_constructor() { + TypeLiteral> listTypeLiteral = new TypeLiteral>() { }; assertEquals(List.class, listTypeLiteral.getRawType()); assertEquals(String.class, TypeLiteral.getTypeParameters(listTypeLiteral.getType())[0]); } @Test - public void test_of(){ - class MyListClass extends ArrayList{} + public void test_of() { + class MyListClass extends ArrayList { } TypeLiteral listTypeLiteral = TypeLiteral.of(MyListClass.class); assertEquals(MyListClass.class, listTypeLiteral.getRawType()); assertEquals(MyListClass.class, listTypeLiteral.getType()); @@ -60,18 +63,28 @@ public void ofDoesNotAcceptNullAsParamter() { } @Test - public void test_getTypeParameter(){ - TypeLiteral> listTypeLiteral = new TypeLiteral>(){}; + public void test_getTypeParameters() { + TypeLiteral> listTypeLiteral = new TypeLiteral>() { }; assertEquals(List.class, listTypeLiteral.getRawType()); assertEquals(String.class, TypeLiteral.getTypeParameters(listTypeLiteral.getType())[0]); } @Test - public void test_getGenericInterfaceTypeParameter(){ - class MyListClass extends ArrayList implements List{} + public void testGetTypeParametersNoGenerics() { + assertEquals(0, getTypeParameters(String.class).length); + } + + @Test + public void test_getGenericInterfaceTypeParameter() { + class MyListClass extends ArrayList implements List { } assertEquals(String.class, getGenericInterfaceTypeParameters(MyListClass.class, List.class)[0]); } + @Test + public void testGetGenericInterfaceTypeParameterNoGenerics() { + assertEquals(0, getGenericInterfaceTypeParameters(String.class, String.class).length); + } + @Test(expected = NullPointerException.class) public void getGenericInterfaceTypeParametersRequiredNonNullValueForClassParameter() { getGenericInterfaceTypeParameters(null, Iterator.class); @@ -87,4 +100,38 @@ public void getTypeParametersRequiresNonNullParameter() { getTypeParameters(null); } + @Test + public void testTypeTakingParametersMustBeSubclassOfParameterizedType() { + //Reflection on ArrayList gives a ParameterizedType + class A extends ArrayList { }; + class B extends A { }; + TypeLiteral> checker = new TypeLiteral>() { }; + Type t = checker.getDefinedType(B.class); + assertEquals(t.getTypeName(), "java.lang.String"); + } + + @Test(expected = RuntimeException.class) + public void testTypeTakingParametersMustNotBeSubclassOfObject() { + //Create a class hierarchy where B is a subclass of Object and not + // ParameterizedType, but still takes parameters. + class A { }; + class B extends A { }; + TypeLiteral> checker = new TypeLiteral>() { }; + checker.getDefinedType(B.class); + } + + @Test + public void testHashAndEquals(){ + TypeLiteral a = TypeLiteral.of(List.class); + TypeLiteral b = TypeLiteral.of(List.class); + TypeLiteral c = TypeLiteral.of(Map.class); + assertEquals(a.hashCode(), b.hashCode()); + assertNotEquals(a.hashCode(), c.hashCode()); + assertTrue(a.equals(a)); + assertTrue(a.equals(b)); + assertFalse(a.equals(null)); + assertFalse(a.equals("SomeString")); + assertFalse(a.equals(c)); + } + } diff --git a/code/api/src/test/java/org/apache/tamaya/spi/ConfigurationProviderSpiTest.java b/code/api/src/test/java/org/apache/tamaya/spi/ConfigurationProviderSpiTest.java new file mode 100644 index 000000000..2e1a8363c --- /dev/null +++ b/code/api/src/test/java/org/apache/tamaya/spi/ConfigurationProviderSpiTest.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spi; + +import org.apache.tamaya.TestConfigurationProvider; +import org.junit.Test; +import static org.junit.Assert.*; +import org.mockito.Mockito; + +public class ConfigurationProviderSpiTest { + +TestConfigurationProvider configProvider = new TestConfigurationProvider(); + + @Test + public void testIsConfigurationSettableByDefault(){ + assertTrue(configProvider.isConfigurationSettable()); + } + + @Test + public void testIsConfigurationContextSettable(){ + assertTrue(configProvider.isConfigurationContextSettable()); + } + + /** + * Test of getConfigurationContext and setConfigurationContext method, of + * class ConfigurationProviderSpi. + */ + @Test + public void testGetSetConfigurationContext() { + ConfigurationContext currentContext = configProvider.getConfigurationContextFromInterface(); + assertTrue(currentContext instanceof ConfigurationContext); + ConfigurationContext newContext = Mockito.mock(ConfigurationContext.class); + try{ + configProvider.setConfigurationContext(newContext); + //The mocked TestConfigurationProvider doesn't set the context on the + // inner Configuration object, as that's deprecated. + assertEquals(newContext, configProvider.getConfigurationContext()); + }finally{ + configProvider.setConfigurationContext(currentContext); + } + } +} diff --git a/code/api/src/test/java/org/apache/tamaya/spi/PropertySourceProviderTest.java b/code/api/src/test/java/org/apache/tamaya/spi/PropertySourceProviderTest.java new file mode 100644 index 000000000..0e8bcfb59 --- /dev/null +++ b/code/api/src/test/java/org/apache/tamaya/spi/PropertySourceProviderTest.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spi; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class PropertySourceProviderTest { + + /** + * Test of EMPTY instance of PropertySourceProvider + */ + @Test + public void testEmptySourceProvider() { + PropertySourceProvider instance = PropertySourceProvider.EMPTY; + assertTrue(instance.getPropertySources().isEmpty()); + assertEquals("PropertySourceProvider(empty)", instance.toString()); + } +} diff --git a/code/api/src/test/java/org/apache/tamaya/spi/PropertySourceTest.java b/code/api/src/test/java/org/apache/tamaya/spi/PropertySourceTest.java new file mode 100644 index 000000000..3b7c0ffb2 --- /dev/null +++ b/code/api/src/test/java/org/apache/tamaya/spi/PropertySourceTest.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spi; + +import java.util.Map; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PropertySourceTest { + + + /** + * Test of EMPTY instance of PropertySource + */ + @Test + public void testEmptySource() { + PropertySource instance = PropertySource.EMPTY; + assertEquals(Integer.MIN_VALUE, instance.getOrdinal()); + assertEquals("", instance.getName()); + assertNull(instance.get("key")); + assertTrue(instance.getProperties().isEmpty()); + assertFalse(instance.isScannable()); + assertEquals("PropertySource.EMPTY", instance.toString()); + + } + + /** + * Test of default isScannable method, of class PropertySource. + */ + @Test + public void testIsScannableByDefault() { + PropertySource instance = new PropertySourceImpl(); + assertEquals(true, instance.isScannable()); + } + + public class PropertySourceImpl implements PropertySource { + + public int getOrdinal() { + return 0; + } + + public String getName() { + return ""; + } + + public PropertyValue get(String key) { + return null; + } + + public Map getProperties() { + return null; + } + } + +} diff --git a/code/api/src/test/java/org/apache/tamaya/spi/PropertyValueBuilderTest.java b/code/api/src/test/java/org/apache/tamaya/spi/PropertyValueBuilderTest.java index cd187dbb5..8f983bc45 100644 --- a/code/api/src/test/java/org/apache/tamaya/spi/PropertyValueBuilderTest.java +++ b/code/api/src/test/java/org/apache/tamaya/spi/PropertyValueBuilderTest.java @@ -18,9 +18,7 @@ */ package org.apache.tamaya.spi; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; @@ -89,7 +87,7 @@ public void setKeyRequiresNonNullParameterForKey() { public void setKeyRequiresNonNullParameterForValue() { new PropertyValueBuilder("a", "b", "s").setValue(null); } - + /* * Tests für addMetaEntries(Map) */ @@ -124,21 +122,26 @@ public void testKey() throws Exception { PropertyValueBuilder b = new PropertyValueBuilder("k", "testKey").setValue("v"); PropertyValue val = b.build(); assertEquals(val.getKey(),"k"); + assertEquals(val.getValue(),"v"); + assertNull(val.getMetaEntries().get("k")); } - + @Test - public void testSource() throws Exception { - PropertyValueBuilder b = new PropertyValueBuilder("k", "testSource").setValue("v"); + public void testSetKey() { + PropertyValueBuilder b = new PropertyValueBuilder("k", "testSetKey").setKey("key"); PropertyValue val = b.build(); - assertEquals(val.getSource(),"testSource"); + assertEquals(val.getKey(),"key"); } @Test - public void testValue() throws Exception { - PropertyValueBuilder b = new PropertyValueBuilder("k", "testValue").setValue("v"); + public void testSource() throws Exception { + PropertyValueBuilder b = new PropertyValueBuilder("k", "testSource").setValue("v"); PropertyValue val = b.build(); - assertEquals(val.getValue(),"v"); - assertNull(val.getMetaEntries().get("k")); + assertEquals(val.getSource(),"testSource"); + + PropertyValueBuilder b2 = b.setSource("differentSource"); + val = b2.build(); + assertEquals(val.getSource(),"differentSource"); } @Test(expected=NullPointerException.class) @@ -157,8 +160,9 @@ public void testSetMetaEntries() throws Exception { .setMetaEntries(meta).build(); assertEquals("v", pv.getValue()); assertEquals("k", pv.getKey()); - assertNull("v2", pv.getMetaEntry("k")); + assertNull(pv.getMetaEntry("k")); assertEquals("testGetKey", pv.getSource()); + assertEquals(2, pv.getMetaEntries().size()); assertEquals("2", pv.getMetaEntry("1")); assertEquals("b", pv.getMetaEntry("a")); } @@ -207,9 +211,11 @@ public void testGetMetaEntries() throws Exception { Map meta = new HashMap<>(); meta.put("1","2"); meta.put("a", "b"); - PropertyValue pv = PropertyValue.builder("k", "testGetKey") + PropertyValueBuilder b = PropertyValue.builder("k", "testGetKey") .setValue("v") - .setMetaEntries(meta).build(); + .setMetaEntries(meta); + PropertyValue pv = b.build(); + assertEquals(meta, b.getMetaEntries()); assertEquals(meta, pv.getMetaEntries()); } @@ -242,5 +248,28 @@ public void testAddContextData() throws Exception { assertNotNull(contextData.getMetaEntry("ts")); assertEquals(contextData.getMetaEntry("y"), "y2"); } + + @Test + public void testMapKey() { + PropertyValueBuilder b = new PropertyValueBuilder("key", "testMapKey") + .setValue("value") + .addMetaEntry("_keyAndThenSome", "mappedvalue") + .addMetaEntry("somethingelse", "othervalue") + .mapKey("mappedkey"); + PropertyValue pv = b.build(); + assertEquals("mappedkey", pv.getKey()); + assertEquals("value", pv.getValue()); + assertEquals(2, pv.getMetaEntries().size()); + assertEquals("mappedvalue", pv.getMetaEntry("_mappedkey.AndThenSome")); + assertEquals("othervalue", pv.getMetaEntry("somethingelse")); + } + + @Test + public void testToString(){ + PropertyValueBuilder b = new PropertyValueBuilder("k") + .setValue("v") + .addMetaEntry("metak", "metav"); + assertEquals("PropertyValueBuilder{key='k'value='v', metaEntries={metak=metav}}", b.toString()); + } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/OSGIActivatorTest.java b/code/core/src/test/java/org/apache/tamaya/core/OSGIActivatorTest.java new file mode 100644 index 000000000..1d59c68e1 --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/OSGIActivatorTest.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core; + +import org.apache.tamaya.Configuration; +import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.core.internal.MockBundle; +import org.apache.tamaya.core.internal.MockBundleContext; +import org.apache.tamaya.spi.ServiceContext; +import org.apache.tamaya.spi.ServiceContextManager; +import org.junit.After; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import org.junit.Before; +import org.junit.Test; +import org.osgi.framework.Bundle; + +/** + * + * @author William.Lieurance 2018-02-05 + */ +public class OSGIActivatorTest { + + ServiceContext prevServiceContext; + Configuration prevConfiguration; + + @Before + public void setUp() throws Exception { + prevServiceContext = ServiceContextManager.getServiceContext(); + prevConfiguration = ConfigurationProvider.getConfiguration(); + } + + @After + public void tearDown() throws Exception { + ServiceContextManager.set(prevServiceContext); + ConfigurationProvider.setConfiguration(prevConfiguration); + } + + /** + * Test of start and stop methods, of class OSGIActivator. + */ + @Test + public void testStartThenStop() { + //Set up the mock + MockBundleContext mockBundleContext = new MockBundleContext(); + MockBundle startedBundle = new MockBundle(); + startedBundle.setState(Bundle.ACTIVE); + startedBundle.setBundleId(1); + startedBundle.setBundleContext(mockBundleContext); + mockBundleContext.installBundle(startedBundle); + OSGIActivator instance = new OSGIActivator(); + + //Start + instance.start(mockBundleContext); + assertEquals(1, mockBundleContext.getBundleListenersCount()); + assertFalse(ConfigurationProvider.getConfiguration().getContext().getPropertyConverters().isEmpty()); + assertNotSame(prevConfiguration, ConfigurationProvider.getConfiguration()); + + //Stop + instance.stop(mockBundleContext); + assertEquals(0, mockBundleContext.getBundleListenersCount()); + } + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/CoreConfigurationBuilderTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/CoreConfigurationBuilderTest.java index 37dc2cbb4..2e9fcd00a 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/CoreConfigurationBuilderTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/CoreConfigurationBuilderTest.java @@ -18,6 +18,13 @@ */ package org.apache.tamaya.core.internal; +import java.io.File; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URI; +import java.net.URL; +import java.nio.file.Path; +import java.util.Collection; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; import org.apache.tamaya.TypeLiteral; @@ -25,7 +32,9 @@ import org.junit.Test; import java.util.Collections; +import java.util.Currency; import java.util.Map; +import org.apache.tamaya.core.internal.converters.BigDecimalConverter; import static org.junit.Assert.*; @@ -52,6 +61,7 @@ public void setConfiguration() throws Exception { assertEquals(cfg, b.build()); } + @Test public void addPropertySources_Array() throws Exception { PropertySource testPS2 = new TestPropertySource("addPropertySources_Array_2"); @@ -173,10 +183,34 @@ public void build() throws Exception { } @Test - public void bla() throws Exception { + public void addDefaultPropertyConverters() throws Exception { ConfigurationBuilder builder = ConfigurationProvider.getConfigurationBuilder(); builder.addDefaultPropertyConverters(); } + + @Test + public void addCorePropertyConverters() throws Exception { + CoreConfigurationBuilder b = new CoreConfigurationBuilder(); + b.addCorePropertyConverters(); + Map, Collection>> converters = b.getPropertyConverter(); + assertTrue(converters.containsKey(TypeLiteral.of(BigDecimal.class))); + assertTrue(converters.containsKey(TypeLiteral.of(BigInteger.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Boolean.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Byte.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Character.class))); + assertTrue(converters.containsKey(TypeLiteral.>of(Class.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Currency.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Double.class))); + assertTrue(converters.containsKey(TypeLiteral.of(File.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Float.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Integer.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Long.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Number.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Path.class))); + assertTrue(converters.containsKey(TypeLiteral.of(Short.class))); + assertTrue(converters.containsKey(TypeLiteral.of(URI.class))); + assertTrue(converters.containsKey(TypeLiteral.of(URL.class))); + } private static class TestPropertySource implements PropertySource{ diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/MockBundle.java b/code/core/src/test/java/org/apache/tamaya/core/internal/MockBundle.java new file mode 100644 index 000000000..415a323ea --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/MockBundle.java @@ -0,0 +1,225 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.cert.X509Certificate; +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.Vector; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.Version; + +/** + * + * @author William.Lieurance 2018-02-05 + */ +public class MockBundle implements Bundle { + + private int state = Bundle.ACTIVE; + + @Override + public int getState() { + return state; + } + + public void setState(int state) { + this.state = state; + } + + @Override + public void start(int i) throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public void start() throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public void stop(int i) throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public void stop() throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public void update(InputStream in) throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public void update() throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public void uninstall() throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public Dictionary getHeaders() { + return new Hashtable<>(); + } + + private long bundleId = 1L; + + @Override + public long getBundleId() { + return bundleId; + } + + public void setBundleId(long bundleId) { + this.bundleId = bundleId; + } + + @Override + public String getLocation() { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public ServiceReference[] getRegisteredServices() { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public ServiceReference[] getServicesInUse() { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public boolean hasPermission(Object o) { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public URL getResource(String string) { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public Dictionary getHeaders(String string) { + return new Hashtable<>(); + } + + @Override + public String getSymbolicName() { + return "MockBundle"; + } + + @Override + public Class loadClass(String string) throws ClassNotFoundException { + if (string.contains("org.something.else") || string.endsWith("/")) { + throw new UnsupportedOperationException("Requested class that should not be requested: " + string); + } + return String.class; + } + + @Override + public Enumeration getResources(String string) throws IOException { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public Enumeration getEntryPaths(String string) { + Vector v = new Vector<>(); + v.add("META-INF/services/" + "someslash/"); + v.add("META-INF/services/" + "org.apache.tamaya"); + v.add("META-INF/services/" + "org.something.else"); + return v.elements(); + } + + @Override + public URL getEntry(String string) { + if (string.equals("META-INF/services/")) { + try { + return new URL("file:///"); + } catch (MalformedURLException ex) { + return null; + } + } + if (string.contains("org.something.else") || string.endsWith("/")) { + throw new UnsupportedOperationException("Requested entry that should not be requested: " + string); + } + return getClass().getClassLoader().getResource("mockbundle.service"); + } + + @Override + public long getLastModified() { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public Enumeration findEntries(String string, String string1, boolean bln) { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + private BundleContext bundleContext = new MockBundleContext(); + + @Override + public BundleContext getBundleContext() { + return bundleContext; + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + @Override + public Map> getSignerCertificates(int i) { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public Version getVersion() { + return new Version(0, 0, 1); + } + + @Override + public A adapt(Class type) { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public File getDataFile(String string) { + throw new UnsupportedOperationException("Not supported (MockBundle)"); + } + + @Override + public int compareTo(Bundle o) { + return Long.compare(this.getBundleId(), o.getBundleId()); + } + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/MockBundleContext.java b/code/core/src/test/java/org/apache/tamaya/core/internal/MockBundleContext.java new file mode 100644 index 000000000..3d16ebf31 --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/MockBundleContext.java @@ -0,0 +1,202 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal; + +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Dictionary; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.BundleListener; +import org.osgi.framework.Filter; +import org.osgi.framework.FrameworkListener; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceListener; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; + +/** + * + * @author William.Lieurance 2018-02-05 + */ +public class MockBundleContext implements BundleContext { + + private ArrayList bundles = new ArrayList<>(); + + @Override + public String getProperty(String string) { + throw new UnsupportedOperationException("Not supported (MockBundleContext getProperty)"); + } + + @Override + public Bundle getBundle() { + return bundles.get(0); + } + + @Override + public Bundle installBundle(String string, InputStream in) throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundleContext installBundle)"); + } + + @Override + public Bundle installBundle(String string) throws BundleException { + throw new UnsupportedOperationException("Not supported (MockBundleContext installBundle)"); + } + + public Bundle installBundle(Bundle bundle) { + bundles.add(bundle); + return bundle; + } + + @Override + public Bundle getBundle(long l) { + return bundles.get(0); + } + + @Override + public Bundle[] getBundles() { + return bundles.toArray(new Bundle[bundles.size()]); + } + + @Override + public void addServiceListener(ServiceListener sl, String string) throws InvalidSyntaxException { + throw new UnsupportedOperationException("Not supported (MockBundleContext addServiceListener)"); + } + + @Override + public void addServiceListener(ServiceListener sl) { + throw new UnsupportedOperationException("Not supported (MockBundleContext addServiceListener)"); + } + + @Override + public void removeServiceListener(ServiceListener sl) { + throw new UnsupportedOperationException("Not supported (MockBundleContext removeServiceListener)"); + } + + int bundleListenersCount = 0; + + public int getBundleListenersCount() { + return bundleListenersCount; + } + + public void setBundleListenersCount(int bundleListenersCount) { + this.bundleListenersCount = bundleListenersCount; + } + + @Override + public void addBundleListener(BundleListener bl) { + bundleListenersCount++; + } + + @Override + public void removeBundleListener(BundleListener bl) { + bundleListenersCount--; + } + + @Override + public void addFrameworkListener(FrameworkListener fl) { + throw new UnsupportedOperationException("Not supported (MockBundleContext addFrameworkListener)"); + } + + @Override + public void removeFrameworkListener(FrameworkListener fl) { + throw new UnsupportedOperationException("Not supported (MockBundleContext removeFrameworkListener)"); + } + + int serviceCount = 0; + + public int getServiceCount() { + return serviceCount; + } + + public void setServiceCount(int serviceCount) { + this.serviceCount = serviceCount; + } + + @Override + public ServiceRegistration registerService(String[] strings, Object o, Dictionary dctnr) { + serviceCount++; + return null; + } + + @Override + public ServiceRegistration registerService(String string, Object o, Dictionary dctnr) { + serviceCount++; + return null; + } + + @Override + public ServiceRegistration registerService(Class type, S s, Dictionary dctnr) { + serviceCount++; + return null; + } + + @Override + public ServiceReference[] getServiceReferences(String string, String string1) throws InvalidSyntaxException { + return new ServiceReference[0]; + } + + @Override + public ServiceReference[] getAllServiceReferences(String string, String string1) throws InvalidSyntaxException { + throw new UnsupportedOperationException("Not supported (MockBundleContext getAllServiceReferences)"); + } + + @Override + public ServiceReference getServiceReference(String string) { + throw new UnsupportedOperationException("Not supported (MockBundleContext getServiceReference)"); + } + + @Override + public ServiceReference getServiceReference(Class type) { + return null; + } + + @Override + public Collection> getServiceReferences(Class type, String string) throws InvalidSyntaxException { + return new ArrayList(); + } + + @Override + public S getService(ServiceReference sr) { + throw new UnsupportedOperationException("Not supported (MockBundleContext getService)"); + } + + @Override + public boolean ungetService(ServiceReference sr) { + throw new UnsupportedOperationException("Not supported (MockBundleContext ungetService)"); + } + + @Override + public File getDataFile(String string) { + throw new UnsupportedOperationException("Not supported (MockBundleContext getDataFile)"); + } + + @Override + public Filter createFilter(String string) throws InvalidSyntaxException { + throw new UnsupportedOperationException("Not supported (MockBundleContext createFilter)"); + } + + @Override + public Bundle getBundle(String string) { + return bundles.get(0); + } +}; diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceComparatorTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceComparatorTest.java new file mode 100644 index 000000000..f956d1ac3 --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceComparatorTest.java @@ -0,0 +1,114 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal; + +import javax.annotation.Priority; +import org.junit.Test; +import static org.junit.Assert.*; +import org.osgi.framework.Bundle; +import org.osgi.framework.ServiceReference; + +/** + * + * @author William.Lieurance 2018-02-05 + */ +public class OSGIServiceComparatorTest { + + /** + * Test of compare method, of class OSGIServiceComparator. + */ + @Test + public void testCompare() { + ServiceReference low = new MockLowPriorityServiceReference(); + ServiceReference nullPriority = new MockServiceReference(); + ServiceReference high = new MockHighPriorityServiceReference(); + OSGIServiceComparator instance = new OSGIServiceComparator(); + + assertEquals(1, instance.compare(low, high)); + assertEquals(-1, instance.compare(high, low)); + assertEquals(0, instance.compare(low, low)); + + assertEquals(1, instance.compare(nullPriority, high)); + assertEquals(-1, instance.compare(high, nullPriority)); + assertEquals(0, instance.compare(nullPriority, low)); + } + + /** + * Test of getPriority method, of class OSGIServiceComparator. + */ + @Test + public void testGetPriority_Object() { + ServiceReference low = new MockLowPriorityServiceReference(); + assertEquals(1, OSGIServiceComparator.getPriority(low)); + + ServiceReference nullPriority = new MockServiceReference(); + assertEquals(1, OSGIServiceComparator.getPriority(nullPriority)); + + ServiceReference high = new MockHighPriorityServiceReference(); + assertEquals(10, OSGIServiceComparator.getPriority(high)); + } + + /** + * Test of getPriority method, of class OSGIServiceComparator. + */ + @Test + public void testGetPriority_Class() { + assertEquals(10, OSGIServiceComparator.getPriority(MockHighPriorityServiceReference.class)); + assertEquals(1, OSGIServiceComparator.getPriority(MockLowPriorityServiceReference.class)); + assertEquals(1, OSGIServiceComparator.getPriority(MockServiceReference.class)); + } + + private class MockServiceReference implements ServiceReference { + @Override + public Object getProperty(String string) { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public String[] getPropertyKeys() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Bundle getBundle() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Bundle[] getUsingBundles() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public boolean isAssignableTo(Bundle bundle, String string) { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public int compareTo(Object o) { + throw new UnsupportedOperationException("Not supported."); + } + } + + @Priority(1) + private class MockLowPriorityServiceReference extends MockServiceReference {}; + @Priority(10) + private class MockHighPriorityServiceReference extends MockServiceReference {}; + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceContextTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceContextTest.java new file mode 100644 index 000000000..25076724f --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceContextTest.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal; + +import java.io.IOException; +import java.net.URL; +import java.util.Enumeration; +import java.util.List; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.mockito.Mockito; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +/** + * + * @author William.Lieurance 2018-02-10 + */ +public class OSGIServiceContextTest { + + /** + * Test of isInitialized method, of class OSGIServiceContext. + */ + @Test + public void testIsInitialized() { + OSGIServiceContext instance = new OSGIServiceContext(Mockito.mock(OSGIServiceLoader.class)); + assertTrue(instance.isInitialized()); + } + + /** + * Test of ordinal method, of class OSGIServiceContext. + */ + @Test + public void testOrdinal() { + OSGIServiceContext instance = new OSGIServiceContext(Mockito.mock(OSGIServiceLoader.class)); + assertEquals(10, instance.ordinal()); + } + + /** + * Test of create method, of class OSGIServiceContext. + */ + @Test + public void testCreateThenGet() { + BundleContext mockBundleContext = new MockBundleContext(); + OSGIServiceLoader loader = new OSGIServiceLoader(mockBundleContext); + OSGIServiceContext instance = new OSGIServiceContext(loader); + + Integer value = instance.create(Integer.class); + assertNull(value); + value = instance.getService(Integer.class); + assertNull(value); + } + + /** + * Test of getServices method, of class OSGIServiceContext. + */ + @Test + public void testGetServices() { + BundleContext mockBundleContext = new MockBundleContext(); + OSGIServiceLoader loader = new OSGIServiceLoader(mockBundleContext); + OSGIServiceContext instance = new OSGIServiceContext(loader); + + List services = instance.getServices(Integer.class); + assertNotNull(services); + assertTrue(services.isEmpty()); + } + + /** + * Test of getResources method, of class OSGIServiceContext. + * @throws java.io.IOException + */ + @Test + public void testGetResources() throws IOException { + MockBundleContext mockBundleContext = new MockBundleContext(); + OSGIServiceLoader loader = new OSGIServiceLoader(mockBundleContext); + MockBundle startedBundle = new MockBundle(); + startedBundle.setState(Bundle.ACTIVE); + startedBundle.setBundleId(1); + startedBundle.setBundleContext(mockBundleContext); + mockBundleContext.installBundle(startedBundle); + OSGIServiceContext instance = new OSGIServiceContext(loader); + + Enumeration resources = instance.getResources("dummy" , ClassLoader.getSystemClassLoader()); + assertNotNull(resources); + URL resource = (URL)resources.nextElement(); + assertTrue(resource.toString().contains("mockbundle.service")); + assertFalse(resources.hasMoreElements()); + } + + /** + * Test of getResource method, of class OSGIServiceContext. + */ + @Test + public void testGetResource() { + MockBundleContext mockBundleContext = new MockBundleContext(); + OSGIServiceLoader loader = new OSGIServiceLoader(mockBundleContext); + MockBundle startedBundle = new MockBundle(); + startedBundle.setState(Bundle.ACTIVE); + startedBundle.setBundleId(1); + startedBundle.setBundleContext(mockBundleContext); + mockBundleContext.installBundle(startedBundle); + OSGIServiceContext instance = new OSGIServiceContext(loader); + + URL resource = instance.getResource("mockbundle.service", ClassLoader.getSystemClassLoader()); + assertNotNull(resource); + assertTrue(resource.toString().contains("mockbundle.service")); + } + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceLoaderTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceLoaderTest.java new file mode 100644 index 000000000..4da6b34c4 --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/OSGIServiceLoaderTest.java @@ -0,0 +1,114 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal; + +import java.util.Set; +import org.junit.Test; +import static org.junit.Assert.*; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; + +/** + * + * @author William.Lieurance 2018-02-06 + */ +public class OSGIServiceLoaderTest { + + /** + * Test of getBundleContext method, of class OSGIServiceLoader. + */ + @Test + public void testGetBundleContext() { + BundleContext mockBundleContext = new MockBundleContext(); + OSGIServiceLoader instance = new OSGIServiceLoader(mockBundleContext); + BundleContext result = instance.getBundleContext(); + assertEquals(mockBundleContext, result); + } + + /** + * Test of getResourceBundles method, of class OSGIServiceLoader. + * + * @throws java.lang.Exception + */ + @Test + public void testGetResourceBundles() throws Exception { + MockBundleContext mockBundleContext = new MockBundleContext(); + MockBundle startedBundle = new MockBundle(); + startedBundle.setState(Bundle.ACTIVE); + startedBundle.setBundleId(1); + startedBundle.setBundleContext(mockBundleContext); + mockBundleContext.installBundle(startedBundle); + OSGIServiceLoader instance = new OSGIServiceLoader(mockBundleContext); + Set result = instance.getResourceBundles(); + assertFalse(result.isEmpty()); + } + + /** + * Test of bundleChanged method, of class OSGIServiceLoader. + * + * @throws java.lang.Exception + */ + @Test + public void testBundleChanged() throws Exception { + //Set up mocks + Set resultBundles; + MockBundleContext mockBundleContext = new MockBundleContext(); + MockBundle startedBundle = new MockBundle(); + startedBundle.setState(Bundle.ACTIVE); + startedBundle.setBundleId(1); + startedBundle.setBundleContext(mockBundleContext); + MockBundle stoppedBundle = new MockBundle(); + stoppedBundle.setState(Bundle.INSTALLED); + stoppedBundle.setBundleId(2); + stoppedBundle.setBundleContext(mockBundleContext); + MockBundle flipBundle = new MockBundle(); + flipBundle.setState(Bundle.INSTALLED); + flipBundle.setBundleId(3); + flipBundle.setBundleContext(mockBundleContext); + mockBundleContext.installBundle(startedBundle); + mockBundleContext.installBundle(stoppedBundle); + mockBundleContext.installBundle(flipBundle); + + //Default case + mockBundleContext.setServiceCount(0); + OSGIServiceLoader instance = new OSGIServiceLoader(mockBundleContext); + resultBundles = instance.getResourceBundles(); + assertEquals(1, resultBundles.size()); + assertEquals(2, mockBundleContext.getServiceCount()); + + //After start + mockBundleContext.setServiceCount(0); + BundleEvent startedEvent = new BundleEvent(BundleEvent.STARTED, flipBundle); + instance.bundleChanged(startedEvent); + resultBundles = instance.getResourceBundles(); + assertEquals(2, resultBundles.size()); + assertEquals(2, mockBundleContext.getServiceCount()); + + //After stop + mockBundleContext.setServiceCount(0); + BundleEvent stoppedEvent = new BundleEvent(BundleEvent.STOPPED, flipBundle); + instance.bundleChanged(stoppedEvent); + resultBundles = instance.getResourceBundles(); + assertEquals(1, resultBundles.size()); + assertEquals(0, mockBundleContext.getServiceCount()); + } + + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BigDecimalConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BigDecimalConverterTest.java index 91d3bb800..5cae3da04 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BigDecimalConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BigDecimalConverterTest.java @@ -65,6 +65,12 @@ public void testConvert_BigDecimal_Hex() throws Exception { valueRead = config.get("tests.converter.bd.hex.upperX", BigDecimal.class); assertThat(valueRead).isNotNull(); assertEquals(new BigDecimal("63"), valueRead); + valueRead = config.get("tests.converter.bd.hex.negLowerX", BigDecimal.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigDecimal("-47"), valueRead); + valueRead = config.get("tests.converter.bd.hex.negUpperX", BigDecimal.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigDecimal("-63"), valueRead); } /** diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BigIntegerConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BigIntegerConverterTest.java new file mode 100644 index 000000000..108159c04 --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BigIntegerConverterTest.java @@ -0,0 +1,161 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal.converters; + +import java.math.BigInteger; +import org.apache.tamaya.ConfigException; +import org.apache.tamaya.Configuration; +import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Ignore; +import static org.mockito.Mockito.mock; + +/** + * + * @author William.Lieurance 2018-02-01 + */ +public class BigIntegerConverterTest { + + /** + * Test conversion. The value are provided by + * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * + * @throws Exception + */ + @Test + public void testConvert_BigInteger_Decimal() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + BigInteger valueRead = config.get("tests.converter.bd.decimal", BigInteger.class); + assertThat(valueRead).isNotNull(); + assertEquals(BigInteger.valueOf(101), valueRead); + } + + /** + * Test conversion. The value are provided by + * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * + * @throws Exception + */ + @Test + public void testConvert_BigInteger_Hex() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + BigInteger valueRead = config.get("tests.converter.bd.hex.lowerX", BigInteger.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigInteger("47"), valueRead); + valueRead = config.get("tests.converter.bd.hex.upperX", BigInteger.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigInteger("63"), valueRead); + valueRead = config.get("tests.converter.bd.hex.negLowerX", BigInteger.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigInteger("-47"), valueRead); + valueRead = config.get("tests.converter.bd.hex.negUpperX", BigInteger.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigInteger("-63"), valueRead); + + } + + /** + * Test conversion. The value are provided by + * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * + * @throws Exception + */ + @Ignore + @Test + public void testConvert_BigInteger_BigHex() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + BigInteger valueRead = config.get("tests.converter.bd.hex.subTenX", BigInteger.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigInteger("16777215"), valueRead); + valueRead = config.get("tests.converter.bd.hex.negSubTenX", BigInteger.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigInteger("-263"), valueRead); + } + + @Test(expected = ConfigException.class) + public void badPositiveHex() { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.bd.hex.badX", BigInteger.class); + } + + @Test(expected = ConfigException.class) + public void badNegativeHex() { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.bd.hex.negBadX", BigInteger.class); + } + + /** + * Test conversion. The value are provided by + * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * + * @throws Exception + */ + @Test + public void testConvert_NotPresent() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + BigInteger valueRead = config.get("tests.converter.bd.foo", BigInteger.class); + assertNull(valueRead); + } + + /** + * Test conversion. The value are provided by + * {@link ConverterTestsPropertySource}. + * + * @throws Exception + */ + @Test + public void testConvert_BigInteger_BigValue() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + BigInteger valueRead = config.get("tests.converter.bd.big", BigInteger.class); + assertThat(valueRead).isNotNull(); + assertEquals(new BigInteger("101666666666666662333337263723628763821638923628193612983618293628763"), + valueRead); + } + + @Test + public void converterHandlesNullValueCorrectly() throws Exception { + ConversionContext context = mock(ConversionContext.class); + + BigIntegerConverter converter = new BigIntegerConverter(); + BigInteger value = converter.convert("", context); + + assertThat(value).isNull(); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(BigInteger.class)).build(); + BigIntegerConverter converter = new BigIntegerConverter(); + BigInteger value = converter.convert("", context); + + assertThat(value).isNull(); + assertTrue(context.getSupportedFormats().contains(" -> new BigInteger(bigint) (BigIntegerConverter)")); + } + + @Test + public void testHashCode() { + BigIntegerConverter instance = new BigIntegerConverter(); + assertEquals(BigIntegerConverter.class.hashCode(), instance.hashCode()); + } + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BooleanConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BooleanConverterTest.java index 46c1e58f1..7accdcd27 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BooleanConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/BooleanConverterTest.java @@ -18,6 +18,7 @@ */ package org.apache.tamaya.core.internal.converters; +import org.apache.tamaya.ConfigException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -25,6 +26,9 @@ import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; +import static org.junit.Assert.assertTrue; import org.junit.Test; /** @@ -35,6 +39,7 @@ public class BooleanConverterTest { /** * Test conversion. The value are provided by * {@link ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -75,6 +80,7 @@ public void testConvert_BooleanTrue() throws Exception { /** * Test conversion. The value are provided by * {@link ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -115,4 +121,34 @@ public void testConvert_BooleanFalse() throws Exception { valueRead = config.get("tests.converter.boolean.foo", Boolean.class); assertNull(valueRead); } + + /** + * Test conversion. The value are provided by + * {@link ConverterTestsPropertySource}. + * + * @throws ConfigException + */ + @Test(expected = ConfigException.class) + public void testConvert_BooleanInvalid() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + Boolean valueRead = config.get("tests.converter.boolean.invalid", Boolean.class); + assertNull(valueRead); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Boolean.class)).build(); + BooleanConverter converter = new BooleanConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains("true (ignore case) (BooleanConverter)")); + assertTrue(context.getSupportedFormats().contains("false (ignore case) (BooleanConverter)")); + } + + @Test + public void testHashCode() { + BooleanConverter instance = new BooleanConverter(); + assertEquals(BooleanConverter.class.hashCode(), instance.hashCode()); + } + } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ByteConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ByteConverterTest.java index 3eb48e347..8eea92da0 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ByteConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ByteConverterTest.java @@ -18,8 +18,11 @@ */ package org.apache.tamaya.core.internal.converters; +import org.apache.tamaya.ConfigException; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; import org.junit.Test; import static org.junit.Assert.*; @@ -78,4 +81,33 @@ public void testConvert_Byte_MaxValue() throws Exception { assertThat(valueRead).isNotNull(); assertEquals(Byte.MAX_VALUE, valueRead.byteValue()); } + /** + * Test conversion. The value are provided by + * {@link ConverterTestsPropertySource}. + * + * @throws ConfigException + */ + @Test(expected = ConfigException.class) + public void testConvert_ByteInvalid() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + Byte valueRead = config.get("tests.converter.byte.invalid", Byte.class); + assertNull(valueRead); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Byte.class)).build(); + ByteConverter converter = new ByteConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains(" (ByteConverter)")); + assertTrue(context.getSupportedFormats().contains("MIN_VALUE (ByteConverter)")); + assertTrue(context.getSupportedFormats().contains("MAX_VALUE (ByteConverter)")); + } + + @Test + public void testHashCode() { + ByteConverter instance = new ByteConverter(); + assertEquals(ByteConverter.class.hashCode(), instance.hashCode()); + } } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/CharConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/CharConverterTest.java index 12810cfc0..9f27582da 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/CharConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/CharConverterTest.java @@ -18,12 +18,16 @@ */ package org.apache.tamaya.core.internal.converters; +import org.apache.tamaya.ConfigException; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; import org.junit.Test; import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*; + /** * Tests conversion of the {@link CharConverter}. */ @@ -42,7 +46,7 @@ public void testConvert_Character_Numeric() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Character valueRead = config.get("tests.converter.char.f-numeric", Character.class); assertThat(valueRead).isNotNull(); - assertEquals(valueRead.charValue(), (char)101); + assertEquals(valueRead.charValue(), (char) 101); } @Test @@ -51,6 +55,7 @@ public void testConvert_Character_Quoted() throws Exception { Character valueRead = config.get("tests.converter.char.d", Character.class); assertThat(valueRead).isNotNull(); assertEquals(valueRead.charValue(), 'd'); + } @Test @@ -61,6 +66,20 @@ public void testConvert_Character_SingleQuote() throws Exception { assertEquals(valueRead.charValue(), '\''); } + @Test(expected = ConfigException.class) + public void testConvert_Character_TwoSingleQuotes() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.char.two-single-quotes", Character.class); + } + + @Test + public void testConvert_Character_ThreeSingleQuotes() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + Character valueRead = config.get("tests.converter.char.three-single-quotes", Character.class); + assertThat(valueRead).isNotNull(); + assertEquals(valueRead.charValue(), '\''); + } + @Test public void testConvert_Character_WithWhitespace_Before() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); @@ -91,4 +110,58 @@ public void testConvert_NotPresent() throws Exception { Character valueRead = config.get("tests.converter.char.foo", Character.class); assertNull(valueRead); } + + /** + * Test conversion. The value are provided by + * {@link ConverterTestsPropertySource}. + * + * @throws ConfigException + */ + @Test + public void testConvert_CharString() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + Character valueRead = config.get("tests.converter.char.invalid", Character.class); + assertThat(valueRead).isNotNull(); + assertEquals(valueRead.charValue(), 'i'); //Strings return the first character + } + + @Test + public void testConvert_CharQuotedString() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + Character valueRead = config.get("tests.converter.char.quoted-invalid", Character.class); + assertThat(valueRead).isNotNull(); + assertEquals(valueRead.charValue(), 'i'); //Strings return the first character + } + + @Test + public void testConvert_CharUnicode() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + Character valueRead = config.get("tests.converter.char.あ", Character.class); + assertThat(valueRead).isNotNull(); + assertEquals(valueRead.charValue(), 'あ'); + } + + @Test + public void testConvert_CharUnicodeString() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + Character valueRead = config.get("tests.converter.char.กขฃคฅฆงจฉช", Character.class); + assertThat(valueRead).isNotNull(); + assertEquals(valueRead.charValue(), 'ก'); //Strings return the first character + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Character.class)).build(); + CharConverter converter = new CharConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains(" (CharConverter)")); + assertTrue(context.getSupportedFormats().contains("\\'\\' (CharConverter)")); + } + + @Test + public void testHashCode() { + CharConverter instance = new CharConverter(); + assertEquals(CharConverter.class.hashCode(), instance.hashCode()); + } } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ClassConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ClassConverterTest.java index 38e150e11..4877d9a6d 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ClassConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ClassConverterTest.java @@ -64,4 +64,19 @@ public void testConvert_NotPresent() throws Exception { assertNull(converter.convert("", context)); assertNull(converter.convert(null, context)); } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(Class.class)).build(); + ClassConverter converter = new ClassConverter(); + converter.convert("", localcontext); + + assertTrue(localcontext.getSupportedFormats().contains(" (ClassConverter)")); + } + + @Test + public void testHashCode() { + ClassConverter instance = new ClassConverter(); + assertEquals(ClassConverter.class.hashCode(), instance.hashCode()); + } } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ConvertQueryTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ConvertQueryTest.java new file mode 100644 index 000000000..26998e3db --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ConvertQueryTest.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal.converters; + +import org.apache.tamaya.Configuration; +import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author William.Lieurance 2018-02-10 + */ +public class ConvertQueryTest { + + /** + * Test of query method, of class ConvertQuery. + */ + @Test + public void testIntegerQuery() { + Configuration config = ConfigurationProvider.getConfiguration(); + ConvertQuery converter = new ConvertQuery<>("101", TypeLiteral.of(Integer.class)); + Integer result = converter.query(config); + assertEquals(101, result.longValue()); + } + + /** + * Test of query method, of class ConvertQuery. + */ + @Test + public void testConfigUsingIntegerQuery() { + Configuration config = ConfigurationProvider.getConfiguration(); + ConvertQuery converter = new ConvertQuery<>("101", TypeLiteral.of(Integer.class)); + Integer result = config.query(converter); + assertEquals(101, result.longValue()); + } + + /** + * Test of query method, of class ConvertQuery. + */ + @Test + public void testNonGenericQuery() { + Configuration config = ConfigurationProvider.getConfiguration(); + + Integer intResult = (Integer) new ConvertQuery("101", TypeLiteral.of(Integer.class)).query(config); + assertEquals(101, intResult.longValue()); + + Boolean booleanResult = (Boolean) new ConvertQuery("true", TypeLiteral.of(Boolean.class)).query(config); + assertEquals(Boolean.TRUE, booleanResult); + } + + /** + * Test of query method, of class ConvertQuery. + */ + @Test + public void testNullWithoutSuccess() { + Configuration config = ConfigurationProvider.getConfiguration(); + + Integer intResult = (Integer) new ConvertQuery("invalid", TypeLiteral.of(Integer.class)).query(config); + assertNull(intResult); + } + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ConverterTestsPropertySource.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ConverterTestsPropertySource.java index dd7649f63..1ef80f1f6 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ConverterTestsPropertySource.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ConverterTestsPropertySource.java @@ -27,7 +27,7 @@ /** * Test Property Source used by converter tests. */ -public class ConverterTestsPropertySource implements PropertySource{ +public class ConverterTestsPropertySource implements PropertySource { @Override public int getOrdinal() { @@ -35,13 +35,13 @@ public int getOrdinal() { } @Override - public String getName(){ + public String getName() { return "ConverterTestsPropertySource"; } @Override public PropertyValue get(String key) { - switch(key){ + switch (key) { // Bytes case "tests.converter.byte.decimal": return PropertyValue.of(key, "101", getName()); @@ -55,6 +55,8 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "min", getName()); case "tests.converter.byte.max": return PropertyValue.of(key, "MAX_Value", getName()); + case "tests.converter.byte.invalid": + return PropertyValue.of(key, "invalid", getName()); // Boolean case "tests.converter.boolean.y1": return PropertyValue.of(key, "y", getName()); @@ -96,13 +98,13 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "f", getName()); case "tests.converter.boolean.f2": return PropertyValue.of(key, "F", getName()); + case "tests.converter.boolean.invalid": + return PropertyValue.of(key, "invalid", getName()); // Character case "tests.converter.char.f": return PropertyValue.of(key, "f", getName()); case "tests.converter.char.d": return PropertyValue.of(key, "'d'", getName()); - case "tests.converter.char.single-quote": - return PropertyValue.of(key, "'", getName()); case "tests.converter.char.f-before": return PropertyValue.of(key, " f", getName()); case "tests.converter.char.f-after": @@ -111,6 +113,21 @@ public PropertyValue get(String key) { return PropertyValue.of(key, " f ", getName()); case "tests.converter.char.f-numeric": return PropertyValue.of(key, "101", getName()); + case "tests.converter.char.single-quote": + return PropertyValue.of(key, "'", getName()); + case "tests.converter.char.two-single-quotes": + return PropertyValue.of(key, "''", getName()); + case "tests.converter.char.three-single-quotes": + return PropertyValue.of(key, "'''", getName()); + case "tests.converter.char.invalid": + return PropertyValue.of(key, "invalid", getName()); + case "tests.converter.char.quoted-invalid": + return PropertyValue.of(key, "'invalid'", getName()); + case "tests.converter.char.あ": + return PropertyValue.of(key, "あ", getName()); + case "tests.converter.char.กขฃคฅฆงจฉช": + return PropertyValue.of(key, "กขฃคฅฆงจฉช", getName()); + // currency case "tests.converter.currency.code1": return PropertyValue.of(key, "CHF", getName()); @@ -138,6 +155,14 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "DE ", getName()); case "tests.converter.currency.code-locale4": return PropertyValue.of(key, " DE ", getName()); + case "tests.converter.currency.code-locale-twopart": + return PropertyValue.of(key, "jp_JP", getName()); + case "tests.converter.currency.code-locale-threepart": + return PropertyValue.of(key, "jp_JP_JP", getName()); + case "tests.converter.currency.code-locale-fourpart": + return PropertyValue.of(key, "jp_JP_JP_JP", getName()); + case "tests.converter.currency.invalid": + return PropertyValue.of(key, "invalid", getName()); //double case "tests.converter.double.decimal": return PropertyValue.of(key, "1.23456789", getName()); @@ -163,6 +188,8 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "positive_infinity", getName()); case "tests.converter.double.ni": return PropertyValue.of(key, "Negative_Infinity", getName()); + case "tests.converter.double.invalid": + return PropertyValue.of(key, "invalid", getName()); //float case "tests.converter.float.decimal": return PropertyValue.of(key, "1.23456789", getName()); @@ -188,6 +215,8 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "positive_infinity", getName()); case "tests.converter.float.ni": return PropertyValue.of(key, "Negative_Infinity", getName()); + case "tests.converter.float.invalid": + return PropertyValue.of(key, "invalid", getName()); // Integer case "tests.converter.integer.decimal": return PropertyValue.of(key, "101", getName()); @@ -201,6 +230,8 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "min", getName()); case "tests.converter.integer.max": return PropertyValue.of(key, "MAX_Value", getName()); + case "tests.converter.integer.invalid": + return PropertyValue.of(key, "invalid", getName()); // Long case "tests.converter.long.decimal": return PropertyValue.of(key, "101", getName()); @@ -214,6 +245,8 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "min", getName()); case "tests.converter.long.max": return PropertyValue.of(key, "MAX_Value", getName()); + case "tests.converter.long.invalid": + return PropertyValue.of(key, "invalid", getName()); // Short case "tests.converter.short.decimal": return PropertyValue.of(key, "101", getName()); @@ -227,7 +260,9 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "min", getName()); case "tests.converter.short.max": return PropertyValue.of(key, "MAX_Value", getName()); - // BigDecimal + case "tests.converter.short.invalid": + return PropertyValue.of(key, "invalid", getName()); + // BigDecimal & BigInteger case "tests.converter.bd.decimal": return PropertyValue.of(key, "101", getName()); case "tests.converter.bd.float": @@ -240,6 +275,21 @@ public PropertyValue get(String key) { return PropertyValue.of(key, "0x2F", getName()); case "tests.converter.bd.hex.upperX": return PropertyValue.of(key, "0X3F", getName()); + case "tests.converter.bd.hex.negLowerX": + return PropertyValue.of(key, "-0x2F", getName()); + case "tests.converter.bd.hex.negUpperX": + return PropertyValue.of(key, "-0X3F", getName()); + case "tests.converter.bd.hex.badX": + return PropertyValue.of(key, "0X3G2", getName()); + case "tests.converter.bd.hex.negBadX": + return PropertyValue.of(key, "-0X3G2", getName()); + case "tests.converter.bd.hex.subTenX": + return PropertyValue.of(key, "0XFFFFFF", getName()); + case "tests.converter.bd.hex.negSubTenX": + return PropertyValue.of(key, "-0X0107", getName()); + case "tests.converter.bd.invalid": + return PropertyValue.of(key, "invalid", getName()); + } return null; } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/CurrencyConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/CurrencyConverterTest.java index f17eaddc9..2541f6639 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/CurrencyConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/CurrencyConverterTest.java @@ -23,6 +23,9 @@ import org.junit.Test; import java.util.Currency; +import org.apache.tamaya.ConfigException; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; @@ -33,12 +36,14 @@ public class CurrencyConverterTest { private static final String BGL = "BGL"; - private static final String CHF = "CHF"; - private static final String EUR = "EUR"; + private static final String CHF = "CHF"; + private static final String EUR = "EUR"; + private static final String JPY = "JPY"; - /** + /** * Test conversion. The values are provided by * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -52,6 +57,7 @@ public void testConvert_Currency_Code_CHF() throws Exception { /** * Test conversion. The values are provided by * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -65,6 +71,7 @@ public void testConvert_Currency_Code_CHF1() throws Exception { /** * Test conversion. The values are provided by * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -78,6 +85,7 @@ public void testConvert_Currency_Code_CHF_Whitespace_Before() throws Exception { /** * Test conversion. The values are provided by * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -91,6 +99,7 @@ public void testConvert_Currency_Code_CHF_Whitespace_After() throws Exception { /** * Test conversion. The values are provided by * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -104,6 +113,7 @@ public void testConvert_Currency_Code_CHF_Whitespace_Around() throws Exception { /** * Test conversion. The values are provided by * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -126,6 +136,7 @@ public void testConvert_Currency_Code_Numeric() throws Exception { /** * Test conversion. The values are provided by * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * * @throws Exception */ @Test @@ -148,12 +159,47 @@ public void testConvert_Currency_Code_Locale() throws Exception { /** * Test conversion. The values are provided by * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * * @throws Exception */ @Test - public void testConvert_NotPresent() throws Exception { + public void testConvert_Currency_Code_Multipart_Locale() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + Currency valueRead = config.get("tests.converter.currency.code-locale-twopart", Currency.class); + assertThat(valueRead).isNotNull(); + assertEquals(JPY, valueRead.getCurrencyCode()); + valueRead = config.get("tests.converter.currency.code-locale-threepart", Currency.class); + assertThat(valueRead).isNotNull(); + assertEquals(JPY, valueRead.getCurrencyCode()); + } + + @Test(expected = ConfigException.class) + public void testConvert_Currency_Code_Fourpart_Locale_Invalid() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + Currency valueRead = config.get("tests.converter.currency.code-locale-fourpart", Currency.class); + assertNull(valueRead); + } + + @Test(expected = ConfigException.class) + public void testConvert_CurrencyInvalid() throws ConfigException { Configuration config = ConfigurationProvider.getConfiguration(); - Byte valueRead = config.get("tests.converter.byte.foo", Byte.class); - assertThat(valueRead).isNull(); + config.get("tests.converter.currency.invalid", Currency.class); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Currency.class)).build(); + CurrencyConverter converter = new CurrencyConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains(" (CurrencyConverter)")); + assertTrue(context.getSupportedFormats().contains(" (CurrencyConverter)")); + assertTrue(context.getSupportedFormats().contains(", using Locale.ENGLISH (CurrencyConverter)")); + } + + @Test + public void testHashCode() { + CurrencyConverter instance = new CurrencyConverter(); + assertEquals(CurrencyConverter.class.hashCode(), instance.hashCode()); } -} \ No newline at end of file +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/DoubleConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/DoubleConverterTest.java index ee2f33a7c..1f5070db8 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/DoubleConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/DoubleConverterTest.java @@ -18,15 +18,18 @@ */ package org.apache.tamaya.core.internal.converters; +import org.apache.tamaya.ConfigException; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; +import static org.junit.Assert.assertEquals; import org.junit.Test; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** - * Tests the default converter for bytes. + * Tests the default converter for doubles. */ public class DoubleConverterTest { @@ -40,7 +43,7 @@ public void testConvert_Double_Decimal() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.decimal", Double.class); assertTrue(valueRead!=null); - assertEquals(valueRead.doubleValue(), 1.23456789, 0.0d); + assertEquals(valueRead, 1.23456789, 0.0d); } /** @@ -53,7 +56,7 @@ public void testConvert_Double_DecimalNegative() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.decimalNegative", Double.class); assertTrue(valueRead!=null); - assertEquals(valueRead.doubleValue(), -1.23456789, 0.0d); + assertEquals(valueRead, -1.23456789, 0.0d); } /** @@ -66,7 +69,7 @@ public void testConvert_Double_Integer() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.integer", Double.class); assertTrue(valueRead!=null); - assertEquals(valueRead.doubleValue(),100d, 0.0d); + assertEquals(valueRead,100d, 0.0d); } /** @@ -79,7 +82,7 @@ public void testConvert_Double_Hex1() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.hex1", Double.class); assertTrue(valueRead!=null); - assertEquals(valueRead.doubleValue(),255d, 0.0d); + assertEquals(valueRead,255d, 0.0d); } /** @@ -92,7 +95,7 @@ public void testConvert_Double_Hex2() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.hex2", Double.class); assertTrue(valueRead!=null); - assertEquals(valueRead.doubleValue(),-255d, 0.0d); + assertEquals(valueRead,-255d, 0.0d); } /** @@ -117,7 +120,7 @@ public void testConvert_Double_MinValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.min", Double.class); assertTrue(valueRead!=null); - assertEquals(Double.MIN_VALUE, valueRead.doubleValue(),0.0d); + assertEquals(Double.MIN_VALUE, valueRead,0.0d); } /** @@ -130,7 +133,7 @@ public void testConvert_Double_MaxValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.max", Double.class); assertTrue(valueRead!=null); - assertEquals(Double.MAX_VALUE, valueRead.doubleValue(),0.0d); + assertEquals(Double.MAX_VALUE, valueRead,0.0d); } /** @@ -143,7 +146,7 @@ public void testConvert_Double_NaNValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.nan", Double.class); assertTrue(valueRead!=null); - assertEquals(Double.NaN, valueRead.doubleValue(),0.0d); + assertEquals(Double.NaN, valueRead,0.0d); } /** @@ -156,7 +159,7 @@ public void testConvert_Double_PositiveInfinityValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.pi", Double.class); assertTrue(valueRead!=null); - assertEquals(Double.POSITIVE_INFINITY, valueRead.doubleValue(),0.0d); + assertEquals(Double.POSITIVE_INFINITY, valueRead,0.0d); } /** @@ -169,7 +172,31 @@ public void testConvert_Double_NegativeInfinityValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Double valueRead = config.get("tests.converter.double.ni", Double.class); assertTrue(valueRead!=null); - assertEquals(Double.NEGATIVE_INFINITY, valueRead.doubleValue(),0.0d); + assertEquals(Double.NEGATIVE_INFINITY, valueRead,0.0d); + } + + + @Test(expected = ConfigException.class) + public void testConvert_DoubleInvalid() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.double.invalid", Double.class); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Double.class)).build(); + DoubleConverter converter = new DoubleConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains(" (DoubleConverter)")); + assertTrue(context.getSupportedFormats().contains("MIN_VALUE (DoubleConverter)")); + assertTrue(context.getSupportedFormats().contains("MAX_VALUE (DoubleConverter)")); + } + + @Test + public void testHashCode() { + DoubleConverter instance = new DoubleConverter(); + assertEquals(DoubleConverter.class.hashCode(), instance.hashCode()); } } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/DurationConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/DurationConverterTest.java index 8a37c0f09..a79913561 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/DurationConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/DurationConverterTest.java @@ -25,6 +25,7 @@ import org.mockito.runners.MockitoJUnitRunner; import java.time.Duration; +import org.apache.tamaya.TypeLiteral; import static org.junit.Assert.*; @@ -76,4 +77,19 @@ public void equalsAndHashcode() throws Exception { assertEquals(conv1.hashCode(), conv2.hashCode()); } + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(Duration.class)).build(); + DurationConverter converter = new DurationConverter(); + converter.convert("", localcontext); + + assertTrue(localcontext.getSupportedFormats().contains("PT20M34S (DurationConverter)")); + } + + @Test + public void testHashCode() { + DurationConverter instance = new DurationConverter(); + assertEquals(DurationConverter.class.hashCode(), instance.hashCode()); + } + } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/FileConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/FileConverterTest.java new file mode 100644 index 000000000..41e372d77 --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/FileConverterTest.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal.converters; + +import java.io.File; +import java.net.URL; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author William.Lieurance 2018-02-01 + */ +public class FileConverterTest { + + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(File.class)).build(); + /** + * Test of convert method, of class FileConverter. + */ + @Test + public void testConvert() { + + FileConverter instance = new FileConverter(); + File result; + + assertNull(instance.convert(null, context)); + + URL testfileUrl = getClass().getResource("/testfile.properties"); + System.out.println(testfileUrl.toString()); + result = instance.convert(testfileUrl.toString(), context); + assertNotNull(result); + assertTrue(context.getSupportedFormats().contains(" (FileConverter)")); + } + + @Test + public void testHashCode(){ + FileConverter instance = new FileConverter(); + assertEquals(FileConverter.class.hashCode(), instance.hashCode()); + } +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/FloatConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/FloatConverterTest.java index 98ea7204a..59e3c554c 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/FloatConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/FloatConverterTest.java @@ -18,11 +18,14 @@ */ package org.apache.tamaya.core.internal.converters; +import org.apache.tamaya.ConfigException; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; +import static org.junit.Assert.assertEquals; import org.junit.Test; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** @@ -40,7 +43,7 @@ public void testConvert_Float_Decimal() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.decimal", Float.class); assertTrue(valueRead!=null); - assertEquals(valueRead.floatValue(), 1.23456789f, 0.0f); + assertEquals(valueRead, 1.23456789f, 0.0f); } /** @@ -53,7 +56,7 @@ public void testConvert_Float_DecimalNegative() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.decimalNegative", Float.class); assertTrue(valueRead!=null); - assertEquals(valueRead.floatValue(), -1.23456789f, 0.0f); + assertEquals(valueRead, -1.23456789f, 0.0f); } /** @@ -66,7 +69,7 @@ public void testConvert_Float_Integer() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.integer", Float.class); assertTrue(valueRead!=null); - assertEquals(valueRead.floatValue(),100f, 0.0f); + assertEquals(valueRead,100f, 0.0f); } /** @@ -79,7 +82,7 @@ public void testConvert_Float_Hex1() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.hex1", Float.class); assertTrue(valueRead!=null); - assertEquals(valueRead.floatValue(),255f, 0.0f); + assertEquals(valueRead,255f, 0.0f); } /** @@ -92,7 +95,7 @@ public void testConvert_Float_Hex2() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.hex2", Float.class); assertTrue(valueRead!=null); - assertEquals(valueRead.floatValue(),-255f, 0.0f); + assertEquals(valueRead,-255f, 0.0f); } /** @@ -105,7 +108,7 @@ public void testConvert_Float_Hex3() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.hex3", Float.class); assertTrue(valueRead!=null); - assertEquals(valueRead.floatValue(),255f, 0.0f); + assertEquals(valueRead,255f, 0.0f); } /** @@ -118,7 +121,7 @@ public void testConvert_Float_MinValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.min", Float.class); assertTrue(valueRead!=null); - assertEquals(Float.MIN_VALUE, valueRead.floatValue(),0.0f); + assertEquals(Float.MIN_VALUE, valueRead,0.0f); } /** @@ -131,7 +134,7 @@ public void testConvert_Float_MaxValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.max", Float.class); assertTrue(valueRead!=null); - assertEquals(Float.MAX_VALUE, valueRead.floatValue(),0.0f); + assertEquals(Float.MAX_VALUE, valueRead,0.0f); } /** @@ -144,7 +147,7 @@ public void testConvert_Float_NaNValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.nan", Float.class); assertTrue(valueRead!=null); - assertEquals(Float.NaN, valueRead.floatValue(),0.0f); + assertEquals(Float.NaN, valueRead,0.0f); } /** @@ -157,7 +160,7 @@ public void testConvert_Float_PositiveInfinityValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.pi", Float.class); assertTrue(valueRead!=null); - assertEquals(Float.POSITIVE_INFINITY, valueRead.floatValue(),0.0f); + assertEquals(Float.POSITIVE_INFINITY, valueRead,0.0f); } /** @@ -170,7 +173,31 @@ public void testConvert_Float_NegativeInfinityValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Float valueRead = config.get("tests.converter.float.ni", Float.class); assertTrue(valueRead!=null); - assertEquals(Float.NEGATIVE_INFINITY, valueRead.floatValue(),0.0f); + assertEquals(Float.NEGATIVE_INFINITY, valueRead,0.0f); + } + + @Test(expected = ConfigException.class) + public void testConvert_FloatInvalid() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.float.invalid", Float.class); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Float.class)).build(); + FloatConverter converter = new FloatConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains(" (FloatConverter)")); + assertTrue(context.getSupportedFormats().contains("MIN_VALUE (FloatConverter)")); + assertTrue(context.getSupportedFormats().contains("MAX_VALUE (FloatConverter)")); + } + + @Test + public void testHashCode() { + FloatConverter instance = new FloatConverter(); + assertEquals(FloatConverter.class.hashCode(), instance.hashCode()); } + } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/InstantConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/InstantConverterTest.java index 4a9a828ed..e3b543dcf 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/InstantConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/InstantConverterTest.java @@ -25,6 +25,7 @@ import org.mockito.runners.MockitoJUnitRunner; import java.time.Instant; +import org.apache.tamaya.TypeLiteral; import static org.junit.Assert.*; @@ -54,4 +55,19 @@ public void equalsAndHashcode() throws Exception { assertEquals(conv1.hashCode(), conv2.hashCode()); } + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(Instant.class)).build(); + InstantConverter converter = new InstantConverter(); + converter.convert("", localcontext); + + assertTrue(localcontext.getSupportedFormats().toString().contains(" (InstantConverter)")); + } + + @Test + public void testHashCode() { + InstantConverter instance = new InstantConverter(); + assertEquals(InstantConverter.class.hashCode(), instance.hashCode()); + } + } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/IntegerConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/IntegerConverterTest.java index 03b0f12b7..9e8e0af77 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/IntegerConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/IntegerConverterTest.java @@ -18,8 +18,11 @@ */ package org.apache.tamaya.core.internal.converters; +import org.apache.tamaya.ConfigException; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; import org.junit.Test; import static org.junit.Assert.*; @@ -108,4 +111,27 @@ public void testConvert_Integer_MaxValue() throws Exception { assertTrue(valueRead != null); assertEquals(Integer.MAX_VALUE, valueRead.intValue()); } + + @Test(expected = ConfigException.class) + public void testConvert_IntegerInvalid() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.integer.invalid", Integer.class); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Integer.class)).build(); + IntegerConverter converter = new IntegerConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains(" (IntegerConverter)")); + assertTrue(context.getSupportedFormats().contains("MIN_VALUE (IntegerConverter)")); + assertTrue(context.getSupportedFormats().contains("MAX_VALUE (IntegerConverter)")); + } + + @Test + public void testHashCode() { + IntegerConverter instance = new IntegerConverter(); + assertEquals(IntegerConverter.class.hashCode(), instance.hashCode()); + } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalDateConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalDateConverterTest.java index 752699d2b..8d7cc0ba4 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalDateConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalDateConverterTest.java @@ -25,6 +25,7 @@ import org.mockito.runners.MockitoJUnitRunner; import java.time.LocalDate; +import org.apache.tamaya.TypeLiteral; import static org.junit.Assert.*; @@ -54,4 +55,18 @@ public void equalsAndHashcode() throws Exception { assertEquals(conv1.hashCode(), conv2.hashCode()); } + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(LocalDate.class)).build(); + LocalDateConverter converter = new LocalDateConverter(); + converter.convert("", localcontext); + + assertTrue(localcontext.getSupportedFormats().toString().contains(" (LocalDateConverter)")); + } + + @Test + public void testHashCode() { + LocalDateConverter instance = new LocalDateConverter(); + assertEquals(LocalDateConverter.class.hashCode(), instance.hashCode()); + } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalDateTimeConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalDateTimeConverterTest.java index 945682ae3..c3355bb21 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalDateTimeConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalDateTimeConverterTest.java @@ -25,6 +25,7 @@ import org.mockito.runners.MockitoJUnitRunner; import java.time.LocalDateTime; +import org.apache.tamaya.TypeLiteral; import static org.junit.Assert.*; @@ -54,4 +55,18 @@ public void equalsAndHashcode() throws Exception { assertEquals(conv1.hashCode(), conv2.hashCode()); } + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(LocalDateTime.class)).build(); + LocalDateTimeConverter converter = new LocalDateTimeConverter(); + converter.convert("", localcontext); + + assertTrue(localcontext.getSupportedFormats().toString().contains(" (LocalDateTimeConverter)")); + } + + @Test + public void testHashCode() { + LocalDateTimeConverter instance = new LocalDateTimeConverter(); + assertEquals(LocalDateTimeConverter.class.hashCode(), instance.hashCode()); + } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalTimeConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalTimeConverterTest.java index b75ed7b2b..b8d2b84b5 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalTimeConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LocalTimeConverterTest.java @@ -25,6 +25,7 @@ import org.mockito.runners.MockitoJUnitRunner; import java.time.LocalTime; +import org.apache.tamaya.TypeLiteral; import static org.junit.Assert.*; @@ -54,4 +55,18 @@ public void equalsAndHashcode() throws Exception { assertEquals(conv1.hashCode(), conv2.hashCode()); } + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(LocalTime.class)).build(); + LocalTimeConverter converter = new LocalTimeConverter(); + converter.convert("", localcontext); + + assertTrue(localcontext.getSupportedFormats().toString().contains(" (LocalTimeConverter)")); + } + + @Test + public void testHashCode() { + LocalTimeConverter instance = new LocalTimeConverter(); + assertEquals(LocalTimeConverter.class.hashCode(), instance.hashCode()); + } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LongConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LongConverterTest.java index 0df6b0918..bb228e62b 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LongConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/LongConverterTest.java @@ -18,8 +18,11 @@ */ package org.apache.tamaya.core.internal.converters; +import org.apache.tamaya.ConfigException; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; import org.junit.Test; import static org.junit.Assert.*; @@ -107,5 +110,28 @@ public void testConvert_Long_MaxValue() throws Exception { Long valueRead = config.get("tests.converter.long.max", Long.class); assertTrue(valueRead != null); assertEquals(Long.MAX_VALUE, valueRead.longValue()); + } + + @Test(expected = ConfigException.class) + public void testConvert_LongInvalid() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.long.invalid", Long.class); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Long.class)).build(); + LongConverter converter = new LongConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains(" (LongConverter)")); + assertTrue(context.getSupportedFormats().contains("MIN_VALUE (LongConverter)")); + assertTrue(context.getSupportedFormats().contains("MAX_VALUE (LongConverter)")); + } + + @Test + public void testHashCode() { + LongConverter instance = new LongConverter(); + assertEquals(LongConverter.class.hashCode(), instance.hashCode()); } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/NumberConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/NumberConverterTest.java index 3fa2e58ae..6131157de 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/NumberConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/NumberConverterTest.java @@ -23,6 +23,9 @@ import org.junit.Test; import java.math.BigDecimal; +import org.apache.tamaya.ConfigException; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; import static org.junit.Assert.*; @@ -40,7 +43,7 @@ public class NumberConverterTest { public void testConvert_Decimal() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Number valueRead = config.get("tests.converter.bd.decimal", Number.class); - assertTrue(valueRead!=null); + assertNotNull(valueRead); assertEquals(valueRead, 101L); } @@ -54,10 +57,10 @@ public void testConvert_Decimal() throws Exception { public void testConvert_Hex() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Number valueRead = config.get("tests.converter.bd.hex.lowerX", Number.class); - assertTrue(valueRead!=null); + assertNotNull(valueRead); assertEquals(valueRead, Long.valueOf("47")); valueRead = config.get("tests.converter.bd.hex.upperX", Number.class); - assertTrue(valueRead!=null); + assertNotNull(valueRead); assertEquals(valueRead, Long.valueOf("63")); } @@ -70,7 +73,7 @@ public void testConvert_Hex() throws Exception { public void testConvert_NotPresent() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Number valueRead = config.get("tests.converter.bd.foo", Number.class); - assertFalse(valueRead!=null); + assertNull(valueRead); } /** @@ -82,7 +85,7 @@ public void testConvert_NotPresent() throws Exception { public void testConvert_BigValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Number valueRead = config.get("tests.converter.bd.big", Number.class); - assertTrue(valueRead!=null); + assertNotNull(valueRead); assertEquals(new BigDecimal("101666666666666662333337263723628763821638923628193612983618293628763"), valueRead); } @@ -96,8 +99,71 @@ public void testConvert_BigValue() throws Exception { public void testConvert_BigFloatValue() throws Exception { Configuration config = ConfigurationProvider.getConfiguration(); Number valueRead = config.get("tests.converter.bd.bigFloat", Number.class); - assertTrue(valueRead!=null); + assertNotNull(valueRead); assertEquals(new BigDecimal("1016666666666666623333372637236287638216389293628763.1016666666666666623333372" + "63723628763821638923628193612983618293628763"), valueRead); } + + /** + * Test conversion. The value are provided by + * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * @throws Exception + */ + @Test + public void testConvert_PositiveInfinityValue() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + Number valueRead = config.get("tests.converter.double.pi", Number.class); + assertNotNull(valueRead); + assertEquals(Double.POSITIVE_INFINITY, valueRead.doubleValue(),0.0d); + } + + /** + * Test conversion. The value are provided by + * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * @throws Exception + */ + @Test + public void testConvert_NegativeInfinityValue() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + Number valueRead = config.get("tests.converter.double.ni", Number.class); + assertNotNull(valueRead); + assertEquals(Double.NEGATIVE_INFINITY, valueRead.doubleValue(),0.0d); + } + + /** + * Test conversion. The value are provided by + * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}. + * @throws Exception + */ + @Test + public void testConvert_NaNValue() throws Exception { + Configuration config = ConfigurationProvider.getConfiguration(); + Number valueRead = config.get("tests.converter.double.nan", Number.class); + assertNotNull(valueRead); + assertEquals(Double.NaN, valueRead.doubleValue(),0.0d); + } + + @Test(expected = ConfigException.class) + public void testConvert_NumberInvalid() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.bd.invalid", Number.class); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Number.class)).build(); + NumberConverter converter = new NumberConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains(", (NumberConverter)")); + assertTrue(context.getSupportedFormats().contains("POSITIVE_INFINITY (NumberConverter)")); + assertTrue(context.getSupportedFormats().contains("NEGATIVE_INFINITY (NumberConverter)")); + assertTrue(context.getSupportedFormats().contains("NAN (NumberConverter)")); + } + + @Test + public void testHashCode() { + NumberConverter instance = new NumberConverter(); + assertEquals(NumberConverter.class.hashCode(), instance.hashCode()); + } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OffsetDateTimeConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OffsetDateTimeConverterTest.java index 4ab65a2fc..fa747beb3 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OffsetDateTimeConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OffsetDateTimeConverterTest.java @@ -18,6 +18,7 @@ */ package org.apache.tamaya.core.internal.converters; +import java.time.LocalDate; import org.apache.tamaya.spi.ConversionContext; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,6 +26,7 @@ import org.mockito.runners.MockitoJUnitRunner; import java.time.OffsetDateTime; +import org.apache.tamaya.TypeLiteral; import static org.junit.Assert.*; @@ -54,4 +56,18 @@ public void equalsAndHashcode() throws Exception { assertEquals(conv1.hashCode(), conv2.hashCode()); } + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(OffsetDateTime.class)).build(); + OffsetDateTimeConverter converter = new OffsetDateTimeConverter(); + converter.convert("", localcontext); + + assertTrue(localcontext.getSupportedFormats().toString().contains(" (OffsetDateTimeConverter)")); + } + + @Test + public void testHashCode() { + OffsetDateTimeConverter instance = new OffsetDateTimeConverter(); + assertEquals(OffsetDateTimeConverter.class.hashCode(), instance.hashCode()); + } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OffsetTimeConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OffsetTimeConverterTest.java index 3b28b2c16..2bf85c910 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OffsetTimeConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OffsetTimeConverterTest.java @@ -25,6 +25,7 @@ import org.mockito.runners.MockitoJUnitRunner; import java.time.OffsetTime; +import org.apache.tamaya.TypeLiteral; import static org.junit.Assert.*; @@ -33,6 +34,7 @@ */ @RunWith(MockitoJUnitRunner.class) public class OffsetTimeConverterTest { + @Mock ConversionContext context; @@ -53,4 +55,18 @@ public void equalsAndHashcode() throws Exception { assertEquals(conv1.hashCode(), conv2.hashCode()); } -} \ No newline at end of file + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(OffsetTime.class)).build(); + OffsetTimeConverter converter = new OffsetTimeConverter(); + converter.convert("", localcontext); + + assertTrue(localcontext.getSupportedFormats().toString().contains(" (OffsetTimeConverter)")); + } + + @Test + public void testHashCode() { + OffsetTimeConverter instance = new OffsetTimeConverter(); + assertEquals(OffsetTimeConverter.class.hashCode(), instance.hashCode()); + } +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OptionalConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OptionalConverterTest.java index f35280b1e..3bcb7b16b 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OptionalConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/OptionalConverterTest.java @@ -18,20 +18,23 @@ */ package org.apache.tamaya.core.internal.converters; +import java.util.List; import org.apache.tamaya.ConfigException; import org.junit.Test; import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; +import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; +import static org.junit.Assert.*; public class OptionalConverterTest { @Test public void nullConversionYieldsEmptyOptional() { final Optional result = new OptionalConverter().convert(null, null); - assertThat(result).isNotNull(); - assertThat(result.isPresent()).isFalse(); + assertNotNull(result); + assertFalse(result.isPresent()); } @Test(expected = ConfigException.class) @@ -39,4 +42,36 @@ public void emulateExceptionWhenGivenContextIsNull() { new OptionalConverter().convert("JustATestValueThatIsIgnored", null); } + @Test + public void testOptionalString() { + TypeLiteral> listOfStringTypeLiteral = new TypeLiteral>() { + }; + ConversionContext ctx = new ConversionContext.Builder("testOptionalString", listOfStringTypeLiteral).build(); + + final Optional result = new OptionalConverter().convert("astring", ctx); + assertNotNull(result); + assertTrue(result.isPresent()); + assertEquals("astring", result.get()); + } + + @Test + public void testOptionalInteger() { + TypeLiteral> listOfIntegerTypeLiteral = new TypeLiteral>() { + }; + ConversionContext ctx = new ConversionContext.Builder("testOptionalInteger", listOfIntegerTypeLiteral) + .setConfiguration(ConfigurationProvider.getConfiguration()) + .build(); + + final Optional result = new OptionalConverter().convert("11", ctx); + assertNotNull(result); + assertTrue(result.isPresent()); + assertEquals(11, result.get().intValue()); + } + + + @Test + public void testHashCode() { + OptionalConverter instance = new OptionalConverter(); + assertEquals(OptionalConverter.class.hashCode(), instance.hashCode()); + } } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/PathConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/PathConverterTest.java index a7f9eab15..534a643cf 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/PathConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/PathConverterTest.java @@ -26,6 +26,7 @@ import java.nio.file.Path; import java.nio.file.Paths; +import org.apache.tamaya.TypeLiteral; import static org.junit.Assert.*; @@ -47,6 +48,22 @@ public void convert() throws Exception { assertNotNull(value); } + @Test + public void convertNull() throws Exception { + PathConverter conv = new PathConverter(); + Path value = conv.convert(null, context); + assertNull(value); + value = conv.convert("", context); + assertNull(value); + } + + @Test + public void convertInvalidPath() throws Exception { + PathConverter conv = new PathConverter(); + Path value = conv.convert("/invalid:/\u0000", context); + assertNull(value); + } + @Test public void equalsAndHashcode() throws Exception { PathConverter conv1 = new PathConverter(); @@ -55,4 +72,18 @@ public void equalsAndHashcode() throws Exception { assertEquals(conv1.hashCode(), conv2.hashCode()); } -} \ No newline at end of file + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(Path.class)).build(); + PathConverter converter = new PathConverter(); + converter.convert("notempty", localcontext); + assertTrue(localcontext.getSupportedFormats().contains(" (PathConverter)")); + } + + @Test + public void testHashCode() { + PathConverter instance = new PathConverter(); + assertEquals(PathConverter.class.hashCode(), instance.hashCode()); + } + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ShortConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ShortConverterTest.java index ca9228dc3..4ee8adacf 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ShortConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/ShortConverterTest.java @@ -18,8 +18,11 @@ */ package org.apache.tamaya.core.internal.converters; +import org.apache.tamaya.ConfigException; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; import org.junit.Test; import static org.junit.Assert.*; @@ -108,4 +111,28 @@ public void testConvert_Short_MaxValue() throws Exception { assertTrue(valueRead != null); assertEquals(Short.MAX_VALUE, valueRead.intValue()); } + + + @Test(expected = ConfigException.class) + public void testConvert_ShortInvalid() throws ConfigException { + Configuration config = ConfigurationProvider.getConfiguration(); + config.get("tests.converter.short.invalid", Short.class); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Short.class)).build(); + ShortConverter converter = new ShortConverter(); + converter.convert("", context); + + assertTrue(context.getSupportedFormats().contains("short (ShortConverter)")); + assertTrue(context.getSupportedFormats().contains("MIN_VALUE (ShortConverter)")); + assertTrue(context.getSupportedFormats().contains("MAX_VALUE (ShortConverter)")); + } + + @Test + public void testHashCode() { + ShortConverter instance = new ShortConverter(); + assertEquals(ShortConverter.class.hashCode(), instance.hashCode()); + } } \ No newline at end of file diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/SupplierConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/SupplierConverterTest.java new file mode 100644 index 000000000..b14a50621 --- /dev/null +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/SupplierConverterTest.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.core.internal.converters; + +import java.net.InetAddress; +import java.util.List; +import java.util.function.Supplier; +import org.apache.tamaya.Configuration; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConversionContext; +import org.apache.tamaya.spi.PropertyConverter; +import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import org.mockito.Mockito; + +/** + * + * @author William.Lieurance 2018-02-01 + */ +public class SupplierConverterTest { + + /** + * Test of convert method, of class SupplierConverter. + */ + @Test + public void testConvert() { + SupplierConverter instance = new SupplierConverter(); + Supplier stringResult; + TypeLiteral listStringTypeLiteral = new TypeLiteral> () {}; + ConversionContext stringContext = new ConversionContext.Builder(listStringTypeLiteral).build(); + + stringResult = instance.convert(null, stringContext); + assertNull(stringResult.get()); + + stringResult = instance.convert("aString", stringContext); + assertEquals("aString", stringResult.get()); + + Supplier addressResult; + + Configuration mockConfig = Mockito.mock(Configuration.class); + Mockito.when(mockConfig.query(any())).thenReturn(Mockito.mock(InetAddress.class)); + + TypeLiteral myConverterTypeLiteral = new TypeLiteral> () {}; + ConversionContext myConverterContext = new ConversionContext.Builder(myConverterTypeLiteral) + .setConfiguration(mockConfig) + .build(); + + addressResult = instance.convert("someKey", myConverterContext); + assertTrue(addressResult.get() instanceof InetAddress); + +} + + @Test + public void testHashCode(){ + SupplierConverter instance = new SupplierConverter(); + assertEquals(SupplierConverter.class.hashCode(), instance.hashCode()); + } + + private class MyConverter implements PropertyConverter { + + @Override + public InetAddress convert(String value, ConversionContext context) { + return Mockito.mock(InetAddress.class); + } + } + +} diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/URIConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/URIConverterTest.java index 10a5236ed..373b97965 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/URIConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/URIConverterTest.java @@ -24,8 +24,12 @@ import java.net.URI; +import org.apache.tamaya.ConfigException; +import org.apache.tamaya.Configuration; +import org.apache.tamaya.ConfigurationProvider; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /** * Tests conversion of the {@link URI}-converter. @@ -65,4 +69,27 @@ public void testConvert_NotPresent() throws Exception { assertNull(converter.convert("", context)); assertNull(converter.convert(null, context)); } + + @Test + public void testConvert_URIInvalid() throws ConfigException { + URIConverter converter = new URIConverter(); + assertNull(converter.convert("not a uri", context)); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(URI.class)).build(); + URIConverter converter = new URIConverter(); + converter.convert("test:path", localcontext); + + assertTrue(localcontext.getSupportedFormats().contains(" -> new URI(uri) (URIConverter)")); + } + + @Test + public void testHashCode() { + URIConverter instance = new URIConverter(); + assertEquals(URIConverter.class.hashCode(), instance.hashCode()); + } + + } diff --git a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/URLConverterTest.java b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/URLConverterTest.java index 3b66a9824..80e5bc97a 100644 --- a/code/core/src/test/java/org/apache/tamaya/core/internal/converters/URLConverterTest.java +++ b/code/core/src/test/java/org/apache/tamaya/core/internal/converters/URLConverterTest.java @@ -25,8 +25,12 @@ import java.net.URI; import java.net.URL; +import org.apache.tamaya.ConfigException; +import org.apache.tamaya.Configuration; +import org.apache.tamaya.ConfigurationProvider; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /** * Tests conversion of the {@link URL}-converter. @@ -66,4 +70,25 @@ public void testConvert_NotPresent() throws Exception { assertNull(converter.convert("", context)); assertNull(converter.convert(null, context)); } + + @Test + public void testConvert_URLInvalid() throws ConfigException { + URLConverter converter = new URLConverter(); + assertNull(converter.convert("not a url", context)); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext localcontext = new ConversionContext.Builder(TypeLiteral.of(URL.class)).build(); + URLConverter converter = new URLConverter(); + converter.convert("http://localhost", localcontext); + + assertTrue(localcontext.getSupportedFormats().contains(" (URLConverter)")); + } + + @Test + public void testHashCode() { + URLConverter instance = new URLConverter(); + assertEquals(URLConverter.class.hashCode(), instance.hashCode()); + } } diff --git a/code/core/src/test/resources/mockbundle.service b/code/core/src/test/resources/mockbundle.service new file mode 100644 index 000000000..985c962d2 --- /dev/null +++ b/code/core/src/test/resources/mockbundle.service @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +java.lang.String +java.lang.String # Has a comment diff --git a/code/spi-support/pom.xml b/code/spi-support/pom.xml index 41358346a..6c4f94dd8 100644 --- a/code/spi-support/pom.xml +++ b/code/spi-support/pom.xml @@ -63,19 +63,5 @@ under the License. - - - - - org.pitest - pitest-maven - - true - - - - diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/BuildablePropertySourceProviderTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/BuildablePropertySourceProviderTest.java index 5f95859f3..7f3cd7a08 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/BuildablePropertySourceProviderTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/BuildablePropertySourceProviderTest.java @@ -18,6 +18,8 @@ */ package org.apache.tamaya.spisupport; +import java.util.Arrays; +import java.util.Iterator; import org.apache.tamaya.spisupport.propertysource.BuildablePropertySource; import org.apache.tamaya.spisupport.propertysource.BuildablePropertySourceProvider; import org.junit.Test; @@ -28,12 +30,18 @@ public class BuildablePropertySourceProviderTest { @Test public void getPropertySources() throws Exception { - BuildablePropertySource ps = BuildablePropertySource.builder() + BuildablePropertySource ps1 = BuildablePropertySource.builder() .withName("test1").build(); + BuildablePropertySource ps2 = BuildablePropertySource.builder() + .withName("test2").build(); BuildablePropertySourceProvider prov = BuildablePropertySourceProvider.builder() - .withPropertySourcs(ps).build(); + .withPropertySourcs(ps1) + .withPropertySourcs(Arrays.asList(ps2)) + .build(); assertNotNull(prov); - assertEquals(prov.getPropertySources().iterator().next(), ps); + Iterator testable = prov.getPropertySources().iterator(); + assertEquals(testable.next(), ps1); + assertEquals(testable.next(), ps2); } @Test @@ -44,12 +52,16 @@ public void equals() throws Exception { .withPropertySourcs(ps).build(); BuildablePropertySourceProvider prov2 = BuildablePropertySourceProvider.builder() .withPropertySourcs(ps).build(); - assertEquals(prov1, prov2); BuildablePropertySource ps2 = BuildablePropertySource.builder() - .withName("test12").build(); - prov2 = BuildablePropertySourceProvider.builder() + .withName("test2").build(); + BuildablePropertySourceProvider prov3 = BuildablePropertySourceProvider.builder() .withPropertySourcs(ps2).build(); - assertNotEquals(prov1, prov2); + + assertEquals(prov1, prov1); + assertEquals(prov1, prov2); + assertNotEquals(prov1, prov3); + assertNotEquals(prov1, null); + assertNotEquals(prov1, "aString"); } @Test diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/BuildablePropertySourceTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/BuildablePropertySourceTest.java index b91cb5971..2983f5c9e 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/BuildablePropertySourceTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/BuildablePropertySourceTest.java @@ -18,6 +18,9 @@ */ package org.apache.tamaya.spisupport; +import java.util.HashMap; +import java.util.Map; +import org.apache.tamaya.spi.PropertyValue; import org.apache.tamaya.spisupport.propertysource.BuildablePropertySource; import org.junit.Test; @@ -46,7 +49,7 @@ public void get() throws Exception { .withSimpleProperty("a", "b").build(); assertEquals("b", ps1.get("a").getValue()); } - + @Test public void getProperties() throws Exception { BuildablePropertySource ps1 = BuildablePropertySource.builder() @@ -55,6 +58,61 @@ public void getProperties() throws Exception { assertEquals(1, ps1.getProperties().size()); assertEquals("b", ps1.getProperties().get("a").getValue()); } + + @Test + public void testScannable() { + BuildablePropertySource bps = BuildablePropertySource.builder().build(); + assertTrue(bps.isScannable()); + } + + @Test + public void testSource() { + BuildablePropertySource bps = BuildablePropertySource.builder() + .withSource("fakeSource") + .withSimpleProperty("defaultSourceKey", "defaultSourceValue") + .withSimpleProperty("namedSourceKey", "namedSourceValue", "namedSource") + .build(); + + assertEquals("fakeSource", bps.get("defaultSourceKey").getSource()); + assertEquals("namedSource", bps.get("namedSourceKey").getSource()); + } + + @Test + public void testWithMaps() { + Map propertyFirst = new HashMap<>(); + propertyFirst.put("firstKey", "firstValue"); + Map propertySecond = new HashMap<>(); + propertySecond.put("secondKey", "secondValue"); + + Map propertyThird = new HashMap<>(); + propertyThird.put("thirdKey", PropertyValue.of("thirdPVKey", "thirdValue", "thirdSource")); + + //This seems wrong + BuildablePropertySource bps = BuildablePropertySource.builder() + .withSimpleProperties(propertyFirst) + .withProperties(propertySecond, "secondSource") + .withProperties(propertyThird) + .build(); + + assertNull(bps.get("firstKey")); + assertNull(bps.get("secondKey")); + assertEquals("thirdValue", bps.get("thirdKey").getValue()); + assertEquals("thirdSource", bps.get("thirdKey").getSource()); + assertNull(bps.get("thirdPVKey")); + + bps = BuildablePropertySource.builder() + .withProperties(propertyThird) + .withSimpleProperties(propertyFirst) + .withProperties(propertySecond, "secondSource") + .build(); + + assertEquals("firstValue", bps.get("firstKey").getValue()); + assertEquals("secondSource", bps.get("secondKey").getSource()); + assertEquals("secondValue", bps.get("secondKey").getValue()); + assertEquals("thirdValue", bps.get("thirdKey").getValue()); + assertEquals("thirdSource", bps.get("thirdKey").getSource()); + assertNull(bps.get("thirdPVKey")); + } @Test public void equals() throws Exception { @@ -66,6 +124,8 @@ public void equals() throws Exception { ps2 = BuildablePropertySource.builder() .withName("test2").build(); assertNotEquals(ps1, ps2); + assertNotEquals(ps2, null); + assertNotEquals(ps1, "aString"); } @Test @@ -83,6 +143,7 @@ public void testHashCode() throws Exception { @Test public void builder() throws Exception { assertNotNull(BuildablePropertySource.builder()); + assertNotNull(BuildablePropertySource.builder().but()); assertNotEquals(BuildablePropertySource.builder(), BuildablePropertySource.builder()); } diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigValueEvaluatorTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigValueEvaluatorTest.java new file mode 100644 index 000000000..e77b99f72 --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigValueEvaluatorTest.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport; + +import java.util.Map; +import org.apache.tamaya.Configuration; +import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.spi.PropertyValue; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author William.Lieurance 2018-02-10 + */ +public class DefaultConfigValueEvaluatorTest { + + + /** + * Test of evaluteRawValue method, of class DefaultConfigValueEvaluator. + */ + @Test + public void testEvaluteRawValue() { + Configuration config = ConfigurationProvider.getConfiguration(); + DefaultConfigValueEvaluator instance = new DefaultConfigValueEvaluator(); + PropertyValue result = instance.evaluteRawValue("confkey1", config.getContext()); + assertEquals("javaconf-value1", result.getValue()); + result = instance.evaluteRawValue("missing", config.getContext()); + assertNull(result); + } + + /** + * Test of evaluateRawValues method, of class DefaultConfigValueEvaluator. + */ + @Test + public void testEvaluateRawValues() { + Configuration config = ConfigurationProvider.getConfiguration(); + DefaultConfigValueEvaluator instance = new DefaultConfigValueEvaluator(); + Map result = instance.evaluateRawValues(config.getContext()); + assertTrue(result.containsKey("confkey1")); + assertEquals("javaconf-value1", result.get("confkey1").getValue()); + } + + +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationBuilderTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationBuilderTest.java index c58696909..a7f408832 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationBuilderTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationBuilderTest.java @@ -18,6 +18,8 @@ */ package org.apache.tamaya.spisupport; +import java.util.Arrays; +import java.util.Collection; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationProvider; import org.apache.tamaya.TypeLiteral; @@ -26,6 +28,7 @@ import org.junit.Test; import java.util.Collections; +import java.util.Comparator; import java.util.Map; import static org.junit.Assert.*; @@ -35,7 +38,8 @@ */ public class DefaultConfigurationBuilderTest { - private TestPropertySource testPropertySource = new TestPropertySource(){}; + private TestPropertySource testPropertySource = new TestPropertySource() { + }; @Test public void setContext() throws Exception { @@ -54,8 +58,8 @@ public void setConfiguration() throws Exception { } @Test - public void addPropertySources_Array() throws Exception { - PropertySource testPS2 = new TestPropertySource("addPropertySources_Array_2"); + public void addRemovePropertySources_Array() throws Exception { + PropertySource testPS2 = new TestPropertySource("addRemovePropertySources_Array"); ConfigurationBuilder b = new DefaultConfigurationBuilder() .addPropertySources(testPropertySource, testPS2); Configuration cfg = b.build(); @@ -63,22 +67,30 @@ public void addPropertySources_Array() throws Exception { assertEquals(2, ctx.getPropertySources().size()); assertTrue(ctx.getPropertySources().contains(testPropertySource)); assertTrue(ctx.getPropertySources().contains(testPS2)); + + b = new DefaultConfigurationBuilder() + .addPropertySources(testPropertySource, testPS2); + cfg = b.removePropertySources(testPropertySource).build(); + ctx = cfg.getContext(); + assertEquals(1, ctx.getPropertySources().size()); + assertFalse(ctx.getPropertySources().contains(testPropertySource)); + assertTrue(ctx.getPropertySources().contains(testPS2)); } @Test - public void removePropertySources_Array() throws Exception { - PropertySource testPS2 = new TestPropertySource("addPropertySources_Array_2"); + public void addRemovePropertySources_Collection() throws Exception { + PropertySource testPS2 = new TestPropertySource("addRemovePropertySources_Collection"); ConfigurationBuilder b = new DefaultConfigurationBuilder() - .addPropertySources(testPropertySource, testPS2); + .addPropertySources(Arrays.asList(testPropertySource, testPS2)); Configuration cfg = b.build(); ConfigurationContext ctx = cfg.getContext(); assertEquals(2, ctx.getPropertySources().size()); assertTrue(ctx.getPropertySources().contains(testPropertySource)); assertTrue(ctx.getPropertySources().contains(testPS2)); + b = new DefaultConfigurationBuilder() .addPropertySources(testPropertySource, testPS2); - b.removePropertySources(testPropertySource); - cfg = b.build(); + cfg = b.removePropertySources(Arrays.asList(testPropertySource)).build(); ctx = cfg.getContext(); assertEquals(1, ctx.getPropertySources().size()); assertFalse(ctx.getPropertySources().contains(testPropertySource)); @@ -86,75 +98,277 @@ public void removePropertySources_Array() throws Exception { } @Test - public void addPropertyFilters_Array() throws Exception { + public void addRemovePropertyFilters_Array() throws Exception { PropertyFilter filter1 = (value, context) -> value; PropertyFilter filter2 = (value, context) -> value; DefaultConfigurationBuilder b = new DefaultConfigurationBuilder(); - b.addPropertyFilters(filter1, filter2); - Configuration cfg = b.build(); + Configuration cfg = b.addPropertyFilters(filter1, filter2).build(); ConfigurationContext ctx = cfg.getContext(); assertTrue(ctx.getPropertyFilters().contains(filter1)); assertTrue(ctx.getPropertyFilters().contains(filter2)); assertEquals(2, ctx.getPropertyFilters().size()); + b = new DefaultConfigurationBuilder(); b.addPropertyFilters(filter1, filter2); - b.addPropertyFilters(filter1, filter2); + cfg = b.addPropertyFilters(filter1, filter2).build(); + ctx = cfg.getContext(); assertEquals(2, ctx.getPropertyFilters().size()); + + b = new DefaultConfigurationBuilder(); + b.addPropertyFilters(filter1, filter2); + cfg = b.removePropertyFilters(filter1).build(); + ctx = cfg.getContext(); + assertEquals(1, ctx.getPropertyFilters().size()); + assertFalse(ctx.getPropertyFilters().contains(filter1)); + assertTrue(ctx.getPropertyFilters().contains(filter2)); + } @Test - public void removePropertyFilters_Array() throws Exception { + public void addRemovePropertyFilters_Collection() throws Exception { PropertyFilter filter1 = (value, context) -> value; PropertyFilter filter2 = (value, context) -> value; - ConfigurationBuilder b = new DefaultConfigurationBuilder() - .addPropertyFilters(filter1, filter2); - Configuration cfg = b.build(); + DefaultConfigurationBuilder b = new DefaultConfigurationBuilder(); + Configuration cfg = b.addPropertyFilters(Arrays.asList(filter1, filter2)).build(); ConfigurationContext ctx = cfg.getContext(); assertTrue(ctx.getPropertyFilters().contains(filter1)); assertTrue(ctx.getPropertyFilters().contains(filter2)); assertEquals(2, ctx.getPropertyFilters().size()); - b = new DefaultConfigurationBuilder() - .addPropertyFilters(filter1, filter2); - b.removePropertyFilters(filter1); - cfg = b.build(); + + b = new DefaultConfigurationBuilder(); + b.addPropertyFilters(Arrays.asList(filter1, filter2, filter1)); + cfg = b.addPropertyFilters(Arrays.asList(filter1, filter2)).build(); + ctx = cfg.getContext(); + assertEquals(2, ctx.getPropertyFilters().size()); + + b = new DefaultConfigurationBuilder(); + b.addPropertyFilters(Arrays.asList(filter1, filter2)); + cfg = b.removePropertyFilters(Arrays.asList(filter1)).build(); ctx = cfg.getContext(); assertEquals(1, ctx.getPropertyFilters().size()); assertFalse(ctx.getPropertyFilters().contains(filter1)); assertTrue(ctx.getPropertyFilters().contains(filter2)); + + } + + @Test + public void increasePriority() { + DefaultConfigurationBuilder b = new DefaultConfigurationBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + b.increasePriority(propertySources[propertySources.length - 1]); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + b.increasePriority(propertySources[propertySources.length - 2]).build(); + for (int i = 0; i < propertySources.length - 2; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + assertEquals(propertySources[propertySources.length - 1], b.getPropertySources().get(propertySources.length - 2)); + assertEquals(propertySources[propertySources.length - 2], b.getPropertySources().get(propertySources.length - 1)); + boolean caughtAlreadyBuilt = false; + try { + b.increasePriority(propertySources[propertySources.length - 2]); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void decreasePriority() { + DefaultConfigurationBuilder b = new DefaultConfigurationBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + b.decreasePriority(propertySources[0]); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + b.decreasePriority(propertySources[1]).build(); + for (int i = 2; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + assertEquals(propertySources[0], b.getPropertySources().get(1)); + assertEquals(propertySources[1], b.getPropertySources().get(0)); + boolean caughtAlreadyBuilt = false; + try { + b.decreasePriority(propertySources[1]); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void lowestPriority() { + // setup + DefaultConfigurationBuilder b = new DefaultConfigurationBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + // test + b.lowestPriority(propertySources[0]); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + b.lowestPriority(propertySources[1]); + for (int i = 2; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + assertEquals(propertySources[0], b.getPropertySources().get(1)); + assertEquals(propertySources[1], b.getPropertySources().get(0)); + b.lowestPriority(propertySources[5]).build(); + assertEquals(propertySources[5], b.getPropertySources().get(0)); + boolean caughtAlreadyBuilt = false; + try { + b.lowestPriority(propertySources[5]); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void highestPriority() { + // setup + DefaultConfigurationBuilder b = new DefaultConfigurationBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + // test + b.highestPriority(propertySources[propertySources.length - 1]); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + b.highestPriority(propertySources[propertySources.length - 2]); + for (int i = 0; i < propertySources.length - 2; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + assertEquals(propertySources[propertySources.length - 2], b.getPropertySources().get(propertySources.length - 1)); + assertEquals(propertySources[propertySources.length - 1], b.getPropertySources().get(propertySources.length - 2)); + b.highestPriority(propertySources[5]).build(); + assertEquals(propertySources[5], b.getPropertySources().get(propertySources.length - 1)); + boolean caughtAlreadyBuilt = false; + try { + b.highestPriority(propertySources[5]); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void sortPropertySources() { + // setup + DefaultConfigurationBuilder b = new DefaultConfigurationBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + Comparator psComp = (o1, o2) -> o1.toString().compareTo(o2.toString()); + // test + assertEquals(DefaultConfigurationBuilder.class, b.sortPropertySources(psComp).getClass()); + Arrays.sort(propertySources, psComp); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + } + + @Test + public void sortPropertyFilter() { + // setup + DefaultConfigurationBuilder b = new DefaultConfigurationBuilder(); + PropertyFilter[] propertyFilters = new PropertyFilter[10]; + for (int i = 0; i < propertyFilters.length; i++) { + propertyFilters[i] = (value, context) -> value.toBuilder().setValue(toString() + " - ").build(); + } + + b.addPropertyFilters(propertyFilters); + Comparator pfComp = (o1, o2) -> o1.toString().compareTo(o2.toString()); + //test + assertEquals(DefaultConfigurationBuilder.class, b.sortPropertyFilter(pfComp).getClass()); + Arrays.sort(propertyFilters, pfComp); + for (int i = 0; i < propertyFilters.length; i++) { + assertEquals(propertyFilters[i], b.getPropertyFilters().get(i)); + } } @Test - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void addPropertyConverter() throws Exception { - PropertyConverter converter = (value, context) -> value.toLowerCase(); - ConfigurationBuilder b = new DefaultConfigurationBuilder() - .addPropertyConverters(TypeLiteral.of(String.class), converter); + public void addRemovePropertyConverter_Array() throws Exception { + PropertyConverter converter1 = (value, context) -> value.toLowerCase(); + PropertyConverter converter2 = (value, context) -> value.toUpperCase(); + ConfigurationBuilder b = new DefaultConfigurationBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), converter1, converter2); Configuration cfg = b.build(); ConfigurationContext ctx = cfg.getContext(); - assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + Map, Collection>> buildConverters = b.getPropertyConverter(); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter1)); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter2)); assertEquals(1, ctx.getPropertyConverters().size()); + assertEquals(2, ctx.getPropertyConverters(TypeLiteral.of(String.class)).size()); + assertTrue(buildConverters.get(TypeLiteral.of(String.class)).containsAll( + ctx.getPropertyConverters().get(TypeLiteral.of(String.class)))); + b = new DefaultConfigurationBuilder() - .addPropertyConverters(TypeLiteral.of(String.class), converter); - b.addPropertyConverters(TypeLiteral.of(String.class), converter); - assertEquals(1, ctx.getPropertyConverters().size()); + .addPropertyConverters(TypeLiteral.of(String.class), converter1); + cfg = b.addPropertyConverters(TypeLiteral.of(String.class), converter1).build(); + ctx = cfg.getContext(); + assertEquals(1, ctx.getPropertyConverters(TypeLiteral.of(String.class)).size()); + + b = new DefaultConfigurationBuilder().addPropertyConverters(TypeLiteral.of(String.class), converter1, converter2); + cfg = b.removePropertyConverters(TypeLiteral.of(String.class), converter1).build(); + ctx = cfg.getContext(); + assertFalse(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter1)); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter2)); + + b = new DefaultConfigurationBuilder().addPropertyConverters(TypeLiteral.of(String.class), converter1, converter2); + cfg = b.removePropertyConverters(TypeLiteral.of(String.class)).build(); + ctx = cfg.getContext(); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).isEmpty()); } @Test - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void removePropertyConverters_Array() throws Exception { - PropertyConverter converter = (value, context) -> value.toLowerCase(); + public void addRemovePropertyConverter_Collection() throws Exception { + PropertyConverter converter1 = (value, context) -> value.toLowerCase(); + PropertyConverter converter2 = (value, context) -> value.toUpperCase(); ConfigurationBuilder b = new DefaultConfigurationBuilder() - .addPropertyConverters(TypeLiteral.of(String.class), converter); + .addPropertyConverters(TypeLiteral.of(String.class), Arrays.asList(converter1, converter2)); Configuration cfg = b.build(); ConfigurationContext ctx = cfg.getContext(); - assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); - assertEquals(1, ctx.getPropertyConverters(TypeLiteral.of(String.class)).size()); + Map, Collection>> buildConverters = b.getPropertyConverter(); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter1)); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter2)); + assertEquals(1, ctx.getPropertyConverters().size()); + assertEquals(2, ctx.getPropertyConverters(TypeLiteral.of(String.class)).size()); + assertTrue(buildConverters.get(TypeLiteral.of(String.class)).containsAll( + ctx.getPropertyConverters().get(TypeLiteral.of(String.class)))); + b = new DefaultConfigurationBuilder() - .addPropertyConverters(TypeLiteral.of(String.class), converter); - b.removePropertyConverters(TypeLiteral.of(String.class), converter); - cfg = b.build(); + .addPropertyConverters(TypeLiteral.of(String.class), Arrays.asList(converter1)); + cfg = b.addPropertyConverters(TypeLiteral.of(String.class), Arrays.asList(converter1)).build(); + ctx = cfg.getContext(); + assertEquals(1, ctx.getPropertyConverters(TypeLiteral.of(String.class)).size()); + + b = new DefaultConfigurationBuilder().addPropertyConverters(TypeLiteral.of(String.class), Arrays.asList(converter1, converter2)); + cfg = b.removePropertyConverters(TypeLiteral.of(String.class), Arrays.asList(converter1)).build(); + ctx = cfg.getContext(); + assertFalse(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter1)); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter2)); + + b = new DefaultConfigurationBuilder().addPropertyConverters(TypeLiteral.of(String.class), Arrays.asList(converter1, converter2)); + cfg = b.removePropertyConverters(TypeLiteral.of(String.class)).build(); ctx = cfg.getContext(); - assertFalse(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).isEmpty()); } @@ -179,15 +393,15 @@ public void bla() throws Exception { builder.addDefaultPropertyConverters(); } - private static class TestPropertySource implements PropertySource{ + private static class TestPropertySource implements PropertySource { private String id; - public TestPropertySource(){ + public TestPropertySource() { this(null); } - public TestPropertySource(String id){ + public TestPropertySource(String id) { this.id = id; } @@ -198,7 +412,7 @@ public int getOrdinal() { @Override public String getName() { - return id!=null?id:"TestPropertySource"; + return id != null ? id : "TestPropertySource"; } @Override @@ -217,4 +431,4 @@ public boolean isScannable() { } } -} \ No newline at end of file +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationContextBuilderTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationContextBuilderTest.java new file mode 100644 index 000000000..b78387768 --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationContextBuilderTest.java @@ -0,0 +1,675 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport; + +import org.apache.tamaya.spi.ConfigurationContext; +import org.apache.tamaya.spi.ConfigurationContextBuilder; +import org.apache.tamaya.spi.PropertyConverter; +import org.apache.tamaya.spi.PropertyFilter; +import org.apache.tamaya.spi.PropertySource; +import org.apache.tamaya.spi.PropertyValueCombinationPolicy; +import static org.junit.Assert.*; + +import org.apache.tamaya.ConfigurationProvider; +import org.apache.tamaya.TypeLiteral; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.ArrayList; + +/** + * + * @author William.Lieurance 2018.02.17 + * + * This class is an almost exact copy of + * com.tamaya.core.internal.CoreConfigurationBuilderTest, which itself uses + * DefaultConfigurationContextBuilder under the covers. + * + */ +public class DefaultConfigurationContextBuilderTest { + + private MockedPropertySource testPropertySource = new MockedPropertySource() { + }; + + @Test + public void setContext() throws Exception { + ConfigurationContext context = ConfigurationProvider.getConfiguration().getContext(); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .setContext(context); + assertEquals(context, b.build()); + boolean caughtAlreadyBuilt = false; + try { + b.setContext(context); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + b = new DefaultConfigurationContextBuilder(context); + assertEquals(context, b.build()); + } + + @Test + public void addPropertySources_Array() throws Exception { + PropertySource testPS2 = new MockedPropertySource("addPropertySources_Array", 1); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertySources(testPropertySource, testPS2); + ConfigurationContext ctx = b.build(); + assertEquals(2, ctx.getPropertySources().size()); + assertTrue(ctx.getPropertySources().contains(testPropertySource)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPropertySource.getName())); + assertTrue(ctx.getPropertySources().contains(testPS2)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPS2.getName())); + // Ensure no sorting happens during add, so switch ordinals! + testPS2 = new MockedPropertySource("addPropertySources_Array", 1); + b = new DefaultConfigurationContextBuilder(); + ctx = b.addPropertySources(testPS2, testPropertySource).build(); + assertEquals(2, ctx.getPropertySources().size()); + assertTrue(ctx.getPropertySources().contains(testPropertySource)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPropertySource.getName())); + assertTrue(ctx.getPropertySources().contains(testPS2)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPS2.getName())); + assertEquals(ctx.getPropertySources().get(1).getName(), "MockedPropertySource"); + assertEquals(ctx.getPropertySources().get(0).getName(), "addPropertySources_Array"); + } + + @Test + public void addPropertySources_Collection() throws Exception { + PropertySource testPS2 = new MockedPropertySource("addPropertySources_Collection", 1); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertySources(Arrays.asList(new PropertySource[]{testPropertySource, testPS2})); + ConfigurationContext ctx = b.build(); + assertEquals(2, ctx.getPropertySources().size()); + assertTrue(ctx.getPropertySources().contains(testPropertySource)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPropertySource.getName())); + assertTrue(ctx.getPropertySources().contains(testPS2)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPS2.getName())); + assertEquals(ctx.getPropertySources().get(0).getName(), "MockedPropertySource"); + assertEquals(ctx.getPropertySources().get(1).getName(), "addPropertySources_Collection"); + // Ensure no sorting happens during add, so switch ordinals! + testPS2 = new MockedPropertySource("addPropertySources_Collection", 1); + ctx = new DefaultConfigurationContextBuilder() + .addPropertySources(Arrays.asList(new PropertySource[]{testPS2, testPropertySource})).build(); + assertEquals(2, ctx.getPropertySources().size()); + assertTrue(ctx.getPropertySources().contains(testPropertySource)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPropertySource.getName())); + assertTrue(ctx.getPropertySources().contains(testPS2)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPS2.getName())); + assertEquals(ctx.getPropertySources().get(1).getName(), "MockedPropertySource"); + assertEquals(ctx.getPropertySources().get(0).getName(), "addPropertySources_Collection"); + } + + @Test + public void removePropertySources_Array() throws Exception { + PropertySource testPS2 = new MockedPropertySource("removePropertySources_Array", 1); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertySources(testPropertySource, testPS2); + ConfigurationContext ctx = b.build(); + assertEquals(2, ctx.getPropertySources().size()); + assertTrue(ctx.getPropertySources().contains(testPropertySource)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPropertySource.getName())); + assertTrue(ctx.getPropertySources().contains(testPS2)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPS2.getName())); + b = new DefaultConfigurationContextBuilder() + .addPropertySources(testPropertySource, testPS2); + ctx = b.removePropertySources(testPropertySource).build(); + assertFalse(ctx.getPropertySources().contains(testPropertySource)); + //Throws an exception + //assertNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPropertySource.getName())); + assertTrue(ctx.getPropertySources().contains(testPS2)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPS2.getName())); + assertEquals(1, ctx.getPropertySources().size()); + } + + @Test + public void removePropertySources_Collection() throws Exception { + PropertySource testPS2 = new MockedPropertySource("removePropertySources_Array", 1); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertySources(testPropertySource, testPS2); + ConfigurationContext ctx = b.build(); + assertEquals(2, ctx.getPropertySources().size()); + assertTrue(ctx.getPropertySources().contains(testPropertySource)); + assertNotNull(((DefaultConfigurationContextBuilder)b).getPropertySource(testPropertySource.getName())); + assertTrue(ctx.getPropertySources().contains(testPS2)); + assertNotNull(ctx.getPropertySource(testPS2.getName())); + b = new DefaultConfigurationContextBuilder() + .addPropertySources(testPropertySource, testPS2); + ctx = b.removePropertySources(testPropertySource).build(); + assertEquals(1, ctx.getPropertySources().size()); + assertFalse(ctx.getPropertySources().contains(testPropertySource)); + assertTrue(ctx.getPropertySources().contains(testPS2)); + assertNotNull(ctx.getPropertySource(testPS2.getName())); + } + + @Test(expected = IllegalArgumentException.class) + public void missingPropertySource() throws Exception { + PropertySource testPS2 = new MockedPropertySource("removePropertySources_Array", 1); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertySources(testPropertySource, testPS2); + assertNull(((DefaultConfigurationContextBuilder)b).getPropertySource("missing")); + } + + @Test + public void addPropertyFilters_Array() throws Exception { + PropertyFilter filter1 = (value, context) -> value; + PropertyFilter filter2 = (value, context) -> value; + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + b.addPropertyFilters(filter1, filter2); + ConfigurationContext ctx = b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.addPropertyFilters(filter1, filter2); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + assertTrue(ctx.getPropertyFilters().contains(filter1)); + assertTrue(ctx.getPropertyFilters().contains(filter2)); + assertEquals(2, ctx.getPropertyFilters().size()); + b = new DefaultConfigurationContextBuilder(); + b.addPropertyFilters(filter1, filter2); + b.addPropertyFilters(filter1, filter2); + assertEquals(2, ctx.getPropertyFilters().size()); + } + + @Test + public void addPropertyFilters_Collection() throws Exception { + PropertyFilter filter1 = (value, context) -> value; + PropertyFilter filter2 = (value, context) -> value; + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + b.addPropertyFilters(Arrays.asList(new PropertyFilter[]{filter1, filter2})); + ConfigurationContext ctx = b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.addPropertyFilters(Arrays.asList(new PropertyFilter[]{filter1, filter2})); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + assertTrue(ctx.getPropertyFilters().contains(filter1)); + assertTrue(ctx.getPropertyFilters().contains(filter2)); + assertEquals(2, ctx.getPropertyFilters().size()); + b = new DefaultConfigurationContextBuilder(); + b.addPropertyFilters(filter1, filter2); + b.addPropertyFilters(filter1, filter2); + assertEquals(2, ctx.getPropertyFilters().size()); + } + + @Test + public void removePropertyFilters_Array() throws Exception { + PropertyFilter filter1 = (value, context) -> value; + PropertyFilter filter2 = (value, context) -> value; + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertyFilters(filter1, filter2); + ConfigurationContext ctx = b.build(); + assertTrue(ctx.getPropertyFilters().contains(filter1)); + assertTrue(ctx.getPropertyFilters().contains(filter2)); + assertEquals(2, ctx.getPropertyFilters().size()); + b = new DefaultConfigurationContextBuilder() + .addPropertyFilters(filter1, filter2); + ctx = b.removePropertyFilters(filter1).build(); + assertEquals(1, ctx.getPropertyFilters().size()); + assertFalse(ctx.getPropertyFilters().contains(filter1)); + assertTrue(ctx.getPropertyFilters().contains(filter2)); + boolean caughtAlreadyBuilt = false; + try { + b.removePropertyFilters(filter1); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void removePropertyFilters_Collection() throws Exception { + PropertyFilter filter1 = (value, context) -> value; + PropertyFilter filter2 = (value, context) -> value; + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertyFilters(Arrays.asList(new PropertyFilter[]{filter1, filter2})); + ConfigurationContext ctx = b.build(); + assertTrue(ctx.getPropertyFilters().contains(filter1)); + assertTrue(ctx.getPropertyFilters().contains(filter2)); + assertEquals(2, ctx.getPropertyFilters().size()); + b = new DefaultConfigurationContextBuilder() + .addPropertyFilters(Arrays.asList(new PropertyFilter[]{filter1, filter2})); + ctx = b.removePropertyFilters(Arrays.asList(filter1)).build(); + assertEquals(1, ctx.getPropertyFilters().size()); + assertFalse(ctx.getPropertyFilters().contains(filter1)); + assertTrue(ctx.getPropertyFilters().contains(filter2)); + boolean caughtAlreadyBuilt = false; + try { + b.removePropertyFilters(filter1); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + @SuppressWarnings({"rawtypes", "unchecked"}) + public void addPropertyConverters_Array() throws Exception { + PropertyConverter converter = (value, context) -> value.toLowerCase(); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), converter); + ConfigurationContext ctx = b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.addPropertyConverters(TypeLiteral.of(String.class), converter); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + assertEquals(1, ctx.getPropertyConverters().size()); + b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), converter); + b.addPropertyConverters(TypeLiteral.of(String.class), converter); + assertEquals(1, ctx.getPropertyConverters().size()); + } + + @Test + @SuppressWarnings({"rawtypes", "unchecked"}) + public void addPropertyConverters_Collection() throws Exception { + PropertyConverter converter = (value, context) -> value.toLowerCase(); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), + Arrays.>asList(new PropertyConverter[]{converter})); + ConfigurationContext ctx = b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.addPropertyConverters(TypeLiteral.of(String.class), + Arrays.>asList(new PropertyConverter[]{converter})); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + assertEquals(ctx.getPropertyConverters().size(), 1); + b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), + Arrays.>asList(new PropertyConverter[]{converter})); + b.addPropertyConverters(TypeLiteral.of(String.class), converter); + assertEquals(ctx.getPropertyConverters().size(), 1); + } + + @Test + @SuppressWarnings({"rawtypes", "unchecked"}) + public void removePropertyConverters_Type() throws Exception { + PropertyConverter converter = (value, context) -> value.toLowerCase(); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), converter); + ConfigurationContext ctx = b.build(); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + assertEquals(1, ctx.getPropertyConverters(TypeLiteral.of(String.class)).size()); + b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), converter); + ctx = b.removePropertyConverters(TypeLiteral.of(String.class)).build(); + assertFalse(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).isEmpty()); + } + + @Test + @SuppressWarnings({"rawtypes", "unchecked"}) + public void removePropertyConverters_Array() throws Exception { + PropertyConverter converter = (value, context) -> value.toLowerCase(); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), converter); + ConfigurationContext ctx = b.build(); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + assertEquals(1, ctx.getPropertyConverters(TypeLiteral.of(String.class)).size()); + b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), converter); + ctx = b.removePropertyConverters(TypeLiteral.of(String.class), converter).build(); + assertFalse(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).isEmpty()); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Test + public void removePropertyConverters_Collection() throws Exception { + PropertyConverter converter = (value, context) -> value.toLowerCase(); + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), Arrays.>asList(new PropertyConverter[]{converter})); + ConfigurationContext ctx = b.build(); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + assertEquals(1, ctx.getPropertyConverters(TypeLiteral.of(String.class)).size()); + b = new DefaultConfigurationContextBuilder() + .addPropertyConverters(TypeLiteral.of(String.class), Arrays.>asList(new PropertyConverter[]{converter})); + ctx = b.removePropertyConverters(TypeLiteral.of(String.class), Arrays.>asList(new PropertyConverter[]{converter})).build(); + assertFalse(ctx.getPropertyConverters(TypeLiteral.of(String.class)).contains(converter)); + assertTrue(ctx.getPropertyConverters(TypeLiteral.of(String.class)).isEmpty()); + } + + @Test + public void setPropertyValueCombinationPolicy() throws Exception { + PropertyValueCombinationPolicy combPol = (currentValue, key, propertySource) -> currentValue; + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder() + .setPropertyValueCombinationPolicy(combPol); + ConfigurationContext ctx = b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.setPropertyValueCombinationPolicy(combPol); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + assertEquals(ctx.getPropertyValueCombinationPolicy(), combPol); + } + + @Test + public void increasePriority() { + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + b.increasePriority(propertySources[propertySources.length - 1]); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + b.increasePriority(propertySources[propertySources.length - 2]).build(); + for (int i = 0; i < propertySources.length - 2; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + assertEquals(propertySources[propertySources.length - 1], b.getPropertySources().get(propertySources.length - 2)); + assertEquals(propertySources[propertySources.length - 2], b.getPropertySources().get(propertySources.length - 1)); + boolean caughtAlreadyBuilt = false; + try { + b.increasePriority(propertySources[propertySources.length - 2]); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void decreasePriority() { + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + b.decreasePriority(propertySources[0]); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + b.decreasePriority(propertySources[1]).build(); + for (int i = 2; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + assertEquals(propertySources[0], b.getPropertySources().get(1)); + assertEquals(propertySources[1], b.getPropertySources().get(0)); + boolean caughtAlreadyBuilt = false; + try { + b.decreasePriority(propertySources[1]); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void lowestPriority() { + // setup + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + // test + b.lowestPriority(propertySources[0]); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + b.lowestPriority(propertySources[1]); + for (int i = 2; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + assertEquals(propertySources[0], b.getPropertySources().get(1)); + assertEquals(propertySources[1], b.getPropertySources().get(0)); + b.lowestPriority(propertySources[5]).build(); + assertEquals(propertySources[5], b.getPropertySources().get(0)); + boolean caughtAlreadyBuilt = false; + try { + b.lowestPriority(propertySources[5]); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void highestPriority() { + // setup + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + // test + b.highestPriority(propertySources[propertySources.length - 1]); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + b.highestPriority(propertySources[propertySources.length - 2]); + for (int i = 0; i < propertySources.length - 2; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + assertEquals(propertySources[propertySources.length - 2], b.getPropertySources().get(propertySources.length - 1)); + assertEquals(propertySources[propertySources.length - 1], b.getPropertySources().get(propertySources.length - 2)); + b.highestPriority(propertySources[5]).build(); + assertEquals(propertySources[5], b.getPropertySources().get(propertySources.length - 1)); + boolean caughtAlreadyBuilt = false; + try { + b.highestPriority(propertySources[5]); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void sortPropertySources() { + // setup + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + MockedPropertySource[] propertySources = new MockedPropertySource[10]; + for (int i = 0; i < propertySources.length; i++) { + propertySources[i] = new MockedPropertySource("ps" + i, i); + } + b.addPropertySources(propertySources); + Comparator psComp = (o1, o2) -> o1.toString().compareTo(o2.toString()); + // test + assertEquals(DefaultConfigurationContextBuilder.class, b.sortPropertySources(psComp).getClass()); + Arrays.sort(propertySources, psComp); + for (int i = 0; i < propertySources.length; i++) { + assertEquals(propertySources[i], b.getPropertySources().get(i)); + } + } + + @Test + public void sortPropertyFilter() { + // setup + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + PropertyFilter[] propertyFilters = new PropertyFilter[10]; + for (int i = 0; i < propertyFilters.length; i++) { + propertyFilters[i] = (value, context) -> value.toBuilder().setValue(toString() + " - ").build(); + } + + b.addPropertyFilters(propertyFilters); + Comparator pfComp = (o1, o2) -> o1.toString().compareTo(o2.toString()); + //test + assertEquals(DefaultConfigurationContextBuilder.class, b.sortPropertyFilter(pfComp).getClass()); + Arrays.sort(propertyFilters, pfComp); + for (int i = 0; i < propertyFilters.length; i++) { + assertEquals(propertyFilters[i], b.getPropertyFilters().get(i)); + } + } + + @Test + public void build() throws Exception { + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + ConfigurationContext ctx = b.build(); + assertNotNull(ctx); + assertTrue(ctx.getPropertySources().isEmpty()); + assertTrue(ctx.getPropertyFilters().isEmpty()); + boolean caughtAlreadyBuilt = false; + try { + b.build(); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + } + + @Test + public void testRemoveAllFilters() throws Exception { + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + b.addPropertyFilters((value, context) -> value.toBuilder().setValue(toString() + " - ").build()); + assertFalse(b.getPropertyFilters().isEmpty()); + b.removePropertyFilters(b.getPropertyFilters()); + assertTrue(b.getPropertyFilters().isEmpty()); + } + + @Test + public void testRemoveAllSources() throws Exception { + ConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + b.addPropertySources(new MockedPropertySource()); + assertFalse(b.getPropertySources().isEmpty()); + b.removePropertySources(b.getPropertySources()); + assertTrue(b.getPropertyFilters().isEmpty()); + } + + @Test + public void testResetContext() throws Exception { + PropertyConverter converter = (value, context) -> value.toLowerCase(); + DefaultConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + ConfigurationContext empty = b.build(); + + b = new DefaultConfigurationContextBuilder(); + b.addPropertyFilters((value, context) -> value.toBuilder().setValue(toString() + " - ").build()); + b.addPropertySources(new MockedPropertySource()); + b.addPropertyConverters(TypeLiteral.of(String.class), converter); + ConfigurationContext full = b.build(); + + boolean caughtAlreadyBuilt = false; + try { + b.resetWithConfigurationContext(empty); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + + b = new DefaultConfigurationContextBuilder(); + b.addPropertyFilters((value, context) -> value.toBuilder().setValue(toString() + " - ").build()); + b.addPropertySources(new MockedPropertySource()); + b.addPropertyConverters(TypeLiteral.of(String.class), converter); + b.resetWithConfigurationContext(empty); + assertTrue(b.getPropertyConverter().isEmpty()); + assertTrue(b.getPropertySources().isEmpty()); + assertTrue(b.getPropertyFilters().isEmpty()); + b.resetWithConfigurationContext(full).build(); + assertFalse(b.getPropertyConverter().isEmpty()); + assertFalse(b.getPropertySources().isEmpty()); + assertFalse(b.getPropertyFilters().isEmpty()); + + } + + @Test + public void testLoadDefaults() throws Exception { + DefaultConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.loadDefaults(); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + + ConfigurationContext ctx = new DefaultConfigurationContextBuilder().loadDefaults().build(); + assertFalse(ctx.getPropertyConverters().isEmpty()); + assertFalse(ctx.getPropertyFilters().isEmpty()); + assertFalse(ctx.getPropertySources().isEmpty()); + } + + + @Test + public void testAddDefaultPropertyConverters() throws Exception { + DefaultConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.addDefaultPropertyConverters(); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + + ConfigurationContext ctx = new DefaultConfigurationContextBuilder().addDefaultPropertyConverters().build(); + assertFalse(ctx.getPropertyConverters().isEmpty()); + assertNotNull(ctx.getPropertyConverters(TypeLiteral.of(Integer.class))); + } + + @Test + public void testAddDefaultPropertyFilters() throws Exception { + DefaultConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.addDefaultPropertyFilters(); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + + ConfigurationContext ctx = new DefaultConfigurationContextBuilder().addDefaultPropertyFilters().build(); + assertFalse(ctx.getPropertyFilters().isEmpty()); + } + + @Test + public void testAddDefaultPropertySources() throws Exception { + DefaultConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + b.build(); + boolean caughtAlreadyBuilt = false; + try { + b.addDefaultPropertySources(); + } catch (IllegalStateException e) { + caughtAlreadyBuilt = true; + } + assertTrue(caughtAlreadyBuilt); + + ConfigurationContext ctx = new DefaultConfigurationContextBuilder().addDefaultPropertySources().build(); + assertFalse(ctx.getPropertySources().isEmpty()); + assertNotNull(ctx.getPropertySource("environment-properties")); + } + + @Test + public void testAddCorePropertyReources() throws Exception { + DefaultConfigurationContextBuilder b = new DefaultConfigurationContextBuilder(); + List ps = new ArrayList<>(); + b.addCorePropertyResources(ps); + assertFalse(ps.isEmpty()); + + } +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationContextTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationContextTest.java new file mode 100644 index 000000000..ee63a3140 --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationContextTest.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport; + +import java.util.List; +import java.util.Map; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConfigurationContextBuilder; +import org.apache.tamaya.spi.PropertyConverter; +import org.apache.tamaya.spi.PropertyFilter; +import org.apache.tamaya.spi.PropertySource; +import org.apache.tamaya.spi.PropertyValueCombinationPolicy; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author William.Lieurance 2018.02.18 + */ +public class DefaultConfigurationContextTest { + + @Test + public void testEqualsAndHashAndToStringValues() { + PropertySource sharedSource = new MockedPropertySource(); + DefaultConfigurationContext ctx1 = (DefaultConfigurationContext) new DefaultConfigurationContextBuilder().build(); + ctx1.addPropertySources(sharedSource); + DefaultConfigurationContext ctx2 = (DefaultConfigurationContext) new DefaultConfigurationContextBuilder().build(); + ctx2.addPropertySources(sharedSource); + DefaultConfigurationContext ctx3 = (DefaultConfigurationContext) new DefaultConfigurationContextBuilder().build(); + ctx3.addPropertySources(new MockedPropertySource()); + + assertEquals(ctx1, ctx1); + assertNotEquals(null, ctx1); + assertNotEquals("aString", ctx1); + assertEquals(ctx1, ctx2); + assertNotEquals(ctx1, ctx3); + assertEquals(ctx1.hashCode(), ctx2.hashCode()); + assertNotEquals(ctx1.hashCode(), ctx3.hashCode()); + String spaces = new String(new char[70 - sharedSource.getName().length()]).replace("\0", " "); + System.out.println(ctx1.toString()); + assertTrue(ctx1.toString().contains(sharedSource.getName() + spaces)); + } +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationTest.java index 4711dc5cd..c05a09ea3 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/DefaultConfigurationTest.java @@ -22,12 +22,9 @@ import org.apache.tamaya.spi.*; import org.junit.Test; -import java.util.Collections; -import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; public class DefaultConfigurationTest { @@ -36,7 +33,7 @@ public class DefaultConfigurationTest { */ @Test(expected = NullPointerException.class) public void getDoesNotAcceptNull() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); c.get(null); } @@ -44,10 +41,10 @@ public void getDoesNotAcceptNull() { /** * Tests for get(String, Class) */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test(expected = NullPointerException.class) + @SuppressWarnings({"rawtypes", "unchecked"}) + @Test(expected = NullPointerException.class) public void getDoesNotAcceptNullForClassTargetType() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); c.get("a", (Class) null); } @@ -57,9 +54,17 @@ public void getDoesNotAcceptNullForClassTargetType() { */ @Test(expected = NullPointerException.class) public void getDoesNotAcceptNullForTypeLiteralTargetType() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); + + c.get("a", (TypeLiteral) null); + } - c.get("a", (TypeLiteral)null); + @Test + public void getReturnsNullOrNotAsAppropriate() { + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); + assertNotNull(c.get("valueOfValid")); + assertNull(c.get("valueOfNull")); + assertNull(c.get("Filternull")); //get does apply filtering } /** @@ -67,24 +72,17 @@ public void getDoesNotAcceptNullForTypeLiteralTargetType() { */ @Test(expected = NullPointerException.class) public void getOrDefaultDoesNotAcceptNullAsKeyForThreeParameterVariant() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); c.getOrDefault(null, String.class, "ok"); } - @Test - public void getOrDefaultDoesAcceptNullAsDefaultValueForThreeParameterVariant() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); - - assertNull(c.getOrDefault("a", String.class, null)); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test(expected = NullPointerException.class) + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test(expected = NullPointerException.class) public void getOrDefaultDoesNotAcceptNullAsTargetTypeForThreeParameterVariant() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); - c.getOrDefault("a", (Class)null, "b"); + c.getOrDefault("a", (Class) null, "b"); } /** @@ -92,21 +90,22 @@ public void getOrDefaultDoesNotAcceptNullAsTargetTypeForThreeParameterVariant() */ @Test(expected = NullPointerException.class) public void getOrDefaultDoesNotAcceptNullAsKeyForThreeParameterVariantSecondIsTypeLiteral() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); c.getOrDefault(null, TypeLiteral.of(String.class), "ok"); } @Test - public void getOrDefaultDoesAcceptNullAsDefaultValueForThreeParameterVariantSecondIsTypeLiteral() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + public void getOrDefaultDoesAcceptNullAsDefaultValueForThreeParameterVariant() { + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); - assertNull(c.getOrDefault("a", TypeLiteral.of(String.class), null)); + assertNotNull(c.getOrDefault("a", String.class, null)); + assertNotNull(c.getOrDefault("a", TypeLiteral.of(String.class), null)); } @Test(expected = NullPointerException.class) public void getOrDefaultDoesNotAcceptNullAsTargetTypeForThreeParameterVariantSecondIsTypeLiteral() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); c.getOrDefault("a", (TypeLiteral) null, "b"); } @@ -116,87 +115,101 @@ public void getOrDefaultDoesNotAcceptNullAsTargetTypeForThreeParameterVariantSec */ @Test(expected = NullPointerException.class) public void getOrDefaultDoesNotAcceptNullAsKeyForTwoParameterVariantDefaultValueIsSecond() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); c.getOrDefault(null, "ok"); } @Test public void getOrDefaultDoesAcceptNullAsDefaultValueForTwoParameterVariantDefaultValueIsSecond() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); - assertNull(c.getOrDefault("a", null)); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); + assertNotNull(c.getOrDefault("a", null)); + } + + @Test + public void getOrDefaultReturnDefaultIfValueWouldHaveBeenNull() { + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); + assertEquals("ok", c.getOrDefault("valueOfNull", "ok")); + assertEquals("ok", c.getOrDefault("valueOfNull", String.class, "ok")); + assertEquals("ok", c.getOrDefault("valueOfNull", TypeLiteral.of(String.class), "ok")); + } + + /** + * Tests for evaluateRawValue(String) + */ + @Test + public void evaluateRawValueReturnsNullOrNotAsAppropriate() { + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); + assertNotNull(c.evaluteRawValue("valueOfValid")); + assertNull(c.evaluteRawValue("valueOfNull")); + assertNotNull(c.evaluteRawValue("Filternull")); //evaluateRawValue does not apply filtering + } + + /** + * Tests for getProperties() + */ + @Test + public void getPropertiesReturnsNullOrNotAsAppropriate() { + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); + Map result = c.getProperties(); + assertEquals("valueFromMockedPropertySource", result.get("someKey")); + assertNull(result.get("notInThePropertiesMock")); + assertNull(result.get("valueOfNull")); + assertNull(result.get("Filternull")); + } + + /** + * Tests for convertValue(String key, String value, TypeLiteral type) + */ + @Test + public void testConvertValue() { + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); + assertTrue(100 == (Integer) c.convertValue("aHundred", "100", TypeLiteral.of(Integer.class))); } @Test(expected = NullPointerException.class) public void with_Null() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); c.with(null); } @Test(expected = NullPointerException.class) public void query_Null() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); c.query(null); } @Test public void with() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); assertEquals(c.with(config -> config), c); } @Test public void query() { - DefaultConfiguration c = new DefaultConfiguration(new DummyConfigurationContext()); + DefaultConfiguration c = new DefaultConfiguration(new MockedConfigurationContext()); assertEquals(c.query(config -> "testQ"), "testQ"); } - - public static class DummyConfigurationContext implements ConfigurationContext { - @Override - public void addPropertySources(PropertySource... propertySources) { - throw new RuntimeException("Method should be never called in this test"); - } - - @Override - public List getPropertySources() { - return Collections.emptyList(); - } - - @Override - public PropertySource getPropertySource(String name) { - throw new RuntimeException("Method should be never called in this test"); - } - - @Override - public void addPropertyConverter(TypeLiteral type, PropertyConverter propertyConverter) { - throw new RuntimeException("Method should be never called in this test"); - } - - @Override - public Map, List>> getPropertyConverters() { - return Collections.emptyMap(); - } - - @Override - public List> getPropertyConverters(TypeLiteral type) { - return Collections.emptyList(); - } - - @Override - public List getPropertyFilters() { - return Collections.emptyList(); - } - - @Override - public PropertyValueCombinationPolicy getPropertyValueCombinationPolicy() { - throw new RuntimeException("Method should be never called in this test"); - } - - @Override - public ConfigurationContextBuilder toBuilder() { - throw new RuntimeException("Method should be never called in this test"); - } - } -} \ No newline at end of file + + @Test + public void testEqualsAndHashAndToStringValues() { + ConfigurationContext sharedContext = new MockedConfigurationContext(); + DefaultConfiguration config1 = new DefaultConfiguration(sharedContext); + DefaultConfiguration config2 = new DefaultConfiguration(sharedContext); + DefaultConfiguration config3 = new DefaultConfiguration(new MockedConfigurationContext()); + + assertEquals(config1, config1); + assertNotEquals(null, config1); + assertNotEquals(sharedContext, config1); + assertNotEquals(config1, sharedContext); + assertNotEquals("aString", config1); + assertEquals(config1, config2); + assertNotEquals(config1, config3); + assertEquals(config1.hashCode(), config2.hashCode()); + assertNotEquals(config1.hashCode(), config3.hashCode()); + assertTrue(config1.toString().contains("Configuration{")); + } + +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/EnumConverterTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/EnumConverterTest.java index 8391c3a52..989c129a5 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/EnumConverterTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/EnumConverterTest.java @@ -24,29 +24,61 @@ import java.math.RoundingMode; import java.util.Arrays; +import java.util.Objects; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /** * Test class testing the {@link EnumConverter} class. */ public class EnumConverterTest { - private final EnumConverter testConverter = new EnumConverter<>(RoundingMode.class); + private final EnumConverter testConverter = new EnumConverter<>(RoundingMode.class); - private final ConversionContext DUMMY_CONTEXT = new ConversionContext.Builder("someKey", TypeLiteral.of(Enum.class)) - .build(); + private final ConversionContext DUMMY_CONTEXT = new ConversionContext.Builder("someKey", TypeLiteral.of(Enum.class)) + .build(); - @Test - public void testConversionWithMixedCasing() { - for (String input : Arrays.asList(RoundingMode.CEILING.toString(), "ceiling", "CeiLinG")) { - assertEquals(RoundingMode.CEILING, testConverter.convert(input, DUMMY_CONTEXT)); - } - } + private enum TEST_ENUM { + A, B, C, D + }; - @Test - public void testConvert_OtherValue() { - assertNull(testConverter.convert("fooBars", DUMMY_CONTEXT)); - } -} \ No newline at end of file + @Test + public void testConversionWithMixedCasing() { + for (String input : Arrays.asList(RoundingMode.CEILING.toString(), "ceiling", "CeiLinG")) { + assertEquals(RoundingMode.CEILING, testConverter.convert(input, DUMMY_CONTEXT)); + } + } + + @Test + public void testConvert_OtherValue() { + assertNull(testConverter.convert("fooBars", DUMMY_CONTEXT)); + } + + @Test + public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { + ConversionContext context = new ConversionContext.Builder("someKey", TypeLiteral.of(Enum.class)).build(); + EnumConverter converter = new EnumConverter<>(RoundingMode.class); + converter.convert("fooBars", context); + + assertTrue(context.getSupportedFormats().contains(" (EnumConverter)")); + } + + @Test + public void testEqualsAndHash() { + EnumConverter converter1 = new EnumConverter<>(RoundingMode.class); + EnumConverter converter2 = new EnumConverter<>(RoundingMode.class); + EnumConverter converter3 = new EnumConverter<>(TEST_ENUM.class); + + assertEquals(converter1, converter1); + assertNotEquals(null, converter1); + assertNotEquals(converter1, "aString"); + assertNotEquals("aString", converter1); + assertEquals(converter1, converter2); + assertNotEquals(converter1, converter3); + assertEquals(converter1.hashCode(), converter2.hashCode()); + assertNotEquals(converter1.hashCode(), converter3.hashCode()); + } +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/IntegerTestConverter.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/IntegerTestConverter.java new file mode 100644 index 000000000..e6e6a2acb --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/IntegerTestConverter.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport; + +import java.util.Objects; +import org.apache.tamaya.spi.ConversionContext; +import org.apache.tamaya.spi.PropertyConverter; + +/** + * Created by William.Lieurance 2018-02-17 + */ +public class IntegerTestConverter implements PropertyConverter { + + @Override + public Integer convert(String value, ConversionContext context) { + context.addSupportedFormats(getClass(), ""); + String trimmed = Objects.requireNonNull(value).trim(); + try { + return Integer.decode(trimmed); + } catch (NumberFormatException e) { + return null; + } + + } +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedConfigurationContext.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedConfigurationContext.java new file mode 100644 index 000000000..29a94927d --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedConfigurationContext.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.spi.ConfigurationContext; +import org.apache.tamaya.spi.ConfigurationContextBuilder; +import org.apache.tamaya.spi.PropertyConverter; +import org.apache.tamaya.spi.PropertyFilter; +import org.apache.tamaya.spi.PropertySource; +import org.apache.tamaya.spi.PropertyValueCombinationPolicy; + +/** + * + * @author William.Lieurance 2018.02.18 + */ +public class MockedConfigurationContext implements ConfigurationContext { + + PropertyConverterManager pcm = new PropertyConverterManager(false); + List pss = new ArrayList<>(); + + public MockedConfigurationContext() { + pcm.register(TypeLiteral.of(Integer.class), new IntegerTestConverter()); + pss.add(new MockedPropertySource()); + } + + @Override + public void addPropertySources(PropertySource... propertySources) { + throw new RuntimeException("addPropertySources should be never called in this test"); + } + + @Override + public List getPropertySources() { + return pss; + } + + @Override + public PropertySource getPropertySource(String name) { + for (PropertySource ps : pss) { + if (ps.getName().equals(name)) { + return ps; + } + } + return null; + } + + @Override + public void addPropertyConverter(TypeLiteral type, PropertyConverter propertyConverter) { + pcm.register(type, propertyConverter); + } + + @Override + public Map, List>> getPropertyConverters() { + return pcm.getPropertyConverters(); + } + + @Override + public List> getPropertyConverters(TypeLiteral type) { + return pcm.getPropertyConverters(type); + } + + @Override + public List getPropertyFilters() { + return Arrays.asList(new MockedPropertyFilter()); + } + + @Override + public PropertyValueCombinationPolicy getPropertyValueCombinationPolicy() { + return PropertyValueCombinationPolicy.DEFAULT_OVERRIDING_POLICY; + } + + @Override + public ConfigurationContextBuilder toBuilder() { + throw new RuntimeException("toBuilder should be never called in this test"); + } +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedPropertyFilter.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedPropertyFilter.java new file mode 100644 index 000000000..9a56476df --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedPropertyFilter.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport; + +import org.apache.tamaya.spi.FilterContext; +import org.apache.tamaya.spi.PropertyFilter; +import org.apache.tamaya.spi.PropertyValue; + +/** + * + * @author William.Lieurance 2018.02.18 + */ +public class MockedPropertyFilter implements PropertyFilter { + + @Override + public PropertyValue filterProperty(PropertyValue value, FilterContext context) { + if (value.getKey().contains("Filternull")) { + return null; + } else { + return value; + } + } +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedPropertySource.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedPropertySource.java new file mode 100644 index 000000000..59ae3cdf2 --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/MockedPropertySource.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport; + +import java.util.HashMap; +import java.util.Map; +import org.apache.tamaya.spi.PropertySource; +import org.apache.tamaya.spi.PropertyValue; + +/** + * + * @author William.Lieurance 2018.02.17 + */ +public class MockedPropertySource implements PropertySource { + + private String name = "MockedPropertySource"; + private int ordinal = 10; + + public MockedPropertySource() { + this("MockedPropertySource", 10); + } + + public MockedPropertySource(String id, int ordinal) { + this.name = id; + this.ordinal = ordinal; + } + + @Override + public int getOrdinal() { + return ordinal; + } + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public PropertyValue get(String key) { + if (key.contains("Null")) { + return PropertyValue.of(key, null, "MockedPropertySource"); + } else if (key.contains("missing")){ + return null; + } + return PropertyValue.of(key, "valueFromMockedPropertySource", "MockedPropertySource"); + } + + @Override + public Map getProperties() { + Map returnable = new HashMap<>(); + returnable.put("shouldBeNull", get("shouldBeNull")); + returnable.put("Filterednull", get("shouldBeFiltered")); + returnable.put("someKey", get("someKey")); + + return returnable; + } + + @Override + public boolean isScannable() { + return true; + } + +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/PropertyConverterManagerTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/PropertyConverterManagerTest.java index 668409a12..116937a94 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/PropertyConverterManagerTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/PropertyConverterManagerTest.java @@ -26,6 +26,7 @@ import java.util.List; +import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -66,6 +67,7 @@ public void factoryMethodOfIsUsedAsConverter() { @Test public void testDirectConverterMapping() { PropertyConverterManager manager = new PropertyConverterManager(true); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(C.class))); List> converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(C.class))); assertThat(converters, hasSize(1)); @@ -80,6 +82,7 @@ public void testDirectConverterMapping() { @Test public void testDirectSuperclassConverterMapping() { PropertyConverterManager manager = new PropertyConverterManager(true); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(B.class))); List> converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(B.class))); assertThat(converters, hasSize(1)); converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(B.class))); @@ -96,6 +99,7 @@ public void testDirectSuperclassConverterMapping() { @Test public void testMultipleConverterLoad() { PropertyConverterManager manager = new PropertyConverterManager(true); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(B.class))); List> converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(B.class))); assertThat(converters, hasSize(1)); manager = new PropertyConverterManager(true); @@ -106,6 +110,7 @@ public void testMultipleConverterLoad() { @Test public void testTransitiveSuperclassConverterMapping() { PropertyConverterManager manager = new PropertyConverterManager(true); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(A.class))); List> converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(A.class))); assertThat(converters, hasSize(1)); @@ -120,6 +125,7 @@ public void testTransitiveSuperclassConverterMapping() { @Test public void testDirectInterfaceMapping() { PropertyConverterManager manager = new PropertyConverterManager(true); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(Readable.class))); List> converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(Readable.class))); assertThat(converters, hasSize(1)); @@ -134,6 +140,7 @@ public void testDirectInterfaceMapping() { @Test public void testTransitiveInterfaceMapping1() { PropertyConverterManager manager = new PropertyConverterManager(true); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(Runnable.class))); List> converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(Runnable.class))); assertThat(converters, hasSize(1)); @@ -148,6 +155,7 @@ public void testTransitiveInterfaceMapping1() { @Test public void testTransitiveInterfaceMapping2() { PropertyConverterManager manager = new PropertyConverterManager(true); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(AutoCloseable.class))); List> converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(AutoCloseable.class))); assertThat(converters, hasSize(1)); @@ -159,6 +167,50 @@ public void testTransitiveInterfaceMapping2() { assertThat(((C) result).getInValue(), equalTo("testTransitiveInterfaceMapping2")); } + @Test + public void testBoxedConverterMapping() { + PropertyConverterManager manager = new PropertyConverterManager(true); + assertFalse(manager.isTargetTypeSupported(TypeLiteral.of(int.class))); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(Integer.class))); + List> converters = List.class.cast(manager.getPropertyConverters(TypeLiteral.of(int.class))); + assertThat(converters, hasSize(1)); + + PropertyConverter converter = converters.get(0); + Integer result = converter.convert("101", DUMMY_CONTEXT); + + assertThat(result, notNullValue()); + assertThat(result, instanceOf(Integer.class)); + assertThat(result, equalTo(101)); + } + + + @Test + public void testCreateEnumPropertyConverter() { + PropertyConverterManager manager = new PropertyConverterManager(false); + PropertyConverter pc = manager.createDefaultPropertyConverter(TypeLiteral.of(MyEnum.class)); + assertTrue(pc instanceof EnumConverter); + assertTrue(manager.isTargetTypeSupported(TypeLiteral.of(MyEnum.class))); + } + + @Test + public void testGetFactoryMethod() throws Exception { + PropertyConverterManager manager = new PropertyConverterManager(false); + Method getFactoryMethod = PropertyConverterManager.class.getDeclaredMethod("getFactoryMethod", new Class[]{Class.class, String[].class}); + getFactoryMethod.setAccessible(true); + + Method foundMethod = (Method) getFactoryMethod.invoke(manager, MyType.class, new String[]{"instanceOf"}); + assertEquals("instanceOf", foundMethod.getName()); + + Method staticOf = (Method) getFactoryMethod.invoke(manager, MyType.class, new String[]{"of"}); + assertEquals("of", staticOf.getName()); + + Method notFoundMethod = (Method) getFactoryMethod.invoke(manager, MyType.class, new String[]{"missingMethod"}); + assertNull(notFoundMethod); + + Method wrongSignature = (Method) getFactoryMethod.invoke(manager, MyType.class, new String[]{"getValue"}); + assertNull(wrongSignature); + } + @Test public void testMapBoxedType() throws Exception { PropertyConverterManager manager = new PropertyConverterManager(false); @@ -199,6 +251,14 @@ public String getValue() { return typeValue; } + public String instanceOf(String input) { + return input; + } + + } + + private enum MyEnum { + A, B, C } } diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/ReflectionUtilTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/ReflectionUtilTest.java new file mode 100644 index 000000000..6f65d1a6a --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/ReflectionUtilTest.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author William.Lieurance 2018-02-11 + */ +public class ReflectionUtilTest { + + private final List reflectable = new ArrayList<>(); + private final Multi multi = new Multi<>(); + + /** + * Test of getParametrizedType method, of class ReflectionUtil. + * @throws java.lang.Exception + */ + @Test + public void testGetParametrizedType() throws Exception { + Field stringListField = this.getClass().getDeclaredField("reflectable"); + ParameterizedType genericListType = (ParameterizedType) stringListField.getGenericType(); + + assertEquals(genericListType.toString(), ReflectionUtil.getParametrizedType(reflectable.getClass()).toString()); + assertEquals(First.class.getName(), ReflectionUtil.getParametrizedType(multi.getClass()).getRawType().getTypeName()); + assertNull(ReflectionUtil.getParametrizedType(Object.class)); + } + + private interface First {} + private interface Second {} + private class Multi implements First, Second {}; + +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/RegexPropertyFilterTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/RegexPropertyFilterTest.java index 2822cb60c..dbc257e32 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/RegexPropertyFilterTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/RegexPropertyFilterTest.java @@ -58,6 +58,21 @@ public void testFilterProperty() throws Exception { assertNotNull(filter.filterProperty(prop1, new FilterContext(prop1, map, configContext))); assertNull(filter.filterProperty(prop2, new FilterContext(prop2, map, configContext))); assertNotNull(filter.filterProperty(prop3, new FilterContext(prop3, map, configContext))); + filter = new RegexPropertyFilter(); + filter.setExcludes("test1.*"); + assertNull(filter.filterProperty(prop1, new FilterContext(prop1, map, configContext))); + assertEquals(filter.filterProperty(prop2, new FilterContext(prop2, map, configContext)), + prop2); + assertNull(filter.filterProperty(prop3, new FilterContext(prop3, map, configContext))); + + filter = new RegexPropertyFilter(); + filter.setIncludes("test1.*"); //Includes overrides Excludes + filter.setExcludes("test1.*"); + assertNotNull(filter.filterProperty(prop1, new FilterContext(prop1, map, configContext))); + assertNull(filter.filterProperty(prop2, new FilterContext(prop2, map, configContext))); + assertNotNull(filter.filterProperty(prop3, new FilterContext(prop3, map, configContext))); + + } @org.junit.Test diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/BasePropertySourceTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/BasePropertySourceTest.java index eb549a405..971dd1cab 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/BasePropertySourceTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/BasePropertySourceTest.java @@ -27,29 +27,20 @@ import java.util.*; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; public class BasePropertySourceTest { @Test public void isAlwaysScanable() { - BasePropertySource bs = new BasePropertySource() { - @Override - public Map getProperties() { - return Collections.emptyMap(); - } - }; + BasePropertySource bs = new EmptyPropertySource(); assertThat(bs.isScannable()).isTrue(); } @Test public void givenOrdinalOverwritesGivenDefaulOrdinal() { - BasePropertySource bs = new BasePropertySource() { - @Override - public Map getProperties() { - return Collections.emptyMap(); - } - }; + BasePropertySource bs = new EmptyPropertySource(); bs.setDefaultOrdinal(10); @@ -94,6 +85,33 @@ public void testGet() { Assert.assertEquals(1000, new OverriddenOrdinalPropertySource().getOrdinal()); } + @Test + public void testEqualsAndHashAndToStringValues() { + BasePropertySource bs1 = new EmptyPropertySource(); + bs1.setName("testEqualsName"); + BasePropertySource bs2 = new EmptyPropertySource(); + bs2.setName("testEqualsName"); + BasePropertySource bs3 = new EmptyPropertySource(); + bs3.setName("testNotEqualsName"); + + assertEquals(bs1, bs1); + assertNotEquals(null, bs1); + assertNotEquals("aString", bs1); + assertEquals(bs1, bs2); + assertNotEquals(bs1, bs3); + assertEquals(bs1.hashCode(), bs2.hashCode()); + assertNotEquals(bs1.hashCode(), bs3.hashCode()); + assertTrue(bs1.toStringValues().contains("name='testEqualsName'")); + } + + private class EmptyPropertySource extends BasePropertySource { + + @Override + public Map getProperties() { + return Collections.emptyMap(); + } + } + private static class OverriddenOrdinalPropertySource extends BasePropertySource { private OverriddenOrdinalPropertySource() { @@ -107,7 +125,7 @@ public String getName() { @Override public Map getProperties() { - Map result = new HashMap<>(1); + Map result = new HashMap<>(1); result.put(PropertySource.TAMAYA_ORDINAL, PropertyValue.of(PropertySource.TAMAYA_ORDINAL, "1000", getName())); return result; } @@ -126,11 +144,10 @@ public String getName() { @Override public Map getProperties() { - Map result = new HashMap<>(1); + Map result = new HashMap<>(1); result.put(PropertySource.TAMAYA_ORDINAL, PropertyValue.of(PropertySource.TAMAYA_ORDINAL, "invalid", getName())); return result; } } - } diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/CLIPropertySourceTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/CLIPropertySourceTest.java index 450777270..7f0b1d21a 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/CLIPropertySourceTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/CLIPropertySourceTest.java @@ -18,7 +18,8 @@ */ package org.apache.tamaya.spisupport.propertysource; -import org.apache.tamaya.spisupport.propertysource.CLIPropertySource; +import java.io.StringReader; +import java.io.StringWriter; import org.junit.Test; import static org.junit.Assert.*; @@ -30,30 +31,59 @@ public class CLIPropertySourceTest { @Test public void setCLIProps() throws Exception { - System.clearProperty("main.args"); - CLIPropertySource ps = new CLIPropertySource(); - assertTrue(ps.getProperties().isEmpty()); - CLIPropertySource.initMainArgs("-a", "b"); - assertFalse(ps.getProperties().isEmpty()); - assertEquals(ps.getProperties().get("a").getValue(), "b"); - CLIPropertySource.initMainArgs("--c"); - assertFalse(ps.getProperties().isEmpty()); - assertEquals(ps.getProperties().get("c").getValue(), "c"); - CLIPropertySource.initMainArgs("sss"); - assertFalse(ps.getProperties().isEmpty()); - assertEquals(ps.getProperties().get("sss").getValue(), "sss"); - CLIPropertySource.initMainArgs("-a", "b", "--c", "sss", "--val=vvv"); - assertFalse(ps.getProperties().isEmpty()); - assertEquals(ps.getProperties().get("a").getValue(), "b"); - assertEquals(ps.getProperties().get("c").getValue(), "c"); - assertEquals(ps.getProperties().get("sss").getValue(), "sss"); - // getProperties() throws Exception { - System.setProperty("main.args", "-a b\t--c sss "); - ps = new CLIPropertySource(); - assertFalse(ps.getProperties().isEmpty()); - System.clearProperty("main.args"); - assertEquals(ps.getProperties().get("a").getValue(), "b"); - assertEquals(ps.getProperties().get("c").getValue(), "c"); - assertEquals(ps.getProperties().get("sss").getValue(), "sss"); + StringWriter stringBufferWriter = new StringWriter(); + System.getProperties().store(stringBufferWriter, null); + String before = stringBufferWriter.toString(); + + try { + System.clearProperty("main.args"); + + CLIPropertySource ps = new CLIPropertySource(); + assertTrue(ps.getProperties().isEmpty()); + + ps = new CLIPropertySource(26); + assertTrue(ps.getProperties().isEmpty()); + assertEquals(26, ps.getOrdinal()); + + ps = new CLIPropertySource("-a", "b"); + assertFalse(ps.getProperties().isEmpty()); + assertEquals(ps.getProperties().get("a").getValue(), "b"); + assertTrue(ps.toStringValues().contains("args=[-a, b]")); + + ps = new CLIPropertySource(16, "-c", "d"); + assertFalse(ps.getProperties().isEmpty()); + assertEquals(ps.getProperties().get("c").getValue(), "d"); + assertEquals(16, ps.getOrdinal()); + + CLIPropertySource.initMainArgs("-e", "f"); + assertFalse(ps.getProperties().isEmpty()); + assertEquals(ps.getProperties().get("e").getValue(), "f"); + + CLIPropertySource.initMainArgs("--g"); + assertFalse(ps.getProperties().isEmpty()); + assertEquals(ps.getProperties().get("g").getValue(), "g"); + + CLIPropertySource.initMainArgs("sss"); + assertFalse(ps.getProperties().isEmpty()); + assertEquals(ps.getProperties().get("sss").getValue(), "sss"); + + CLIPropertySource.initMainArgs("-a", "b", "--c", "sss", "--val=vvv"); + assertFalse(ps.getProperties().isEmpty()); + assertEquals(ps.getProperties().get("a").getValue(), "b"); + assertEquals(ps.getProperties().get("c").getValue(), "c"); + assertEquals(ps.getProperties().get("sss").getValue(), "sss"); + + System.setProperty("main.args", "-a b\t--c sss "); + ps = new CLIPropertySource(); + assertFalse(ps.getProperties().isEmpty()); + System.clearProperty("main.args"); + assertEquals(ps.getProperties().get("a").getValue(), "b"); + assertEquals(ps.getProperties().get("c").getValue(), "c"); + assertEquals(ps.getProperties().get("sss").getValue(), "sss"); + + } finally { + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + } } -} \ No newline at end of file +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/EnvironmentPropertySourceTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/EnvironmentPropertySourceTest.java index 1e6c95820..3e57d1687 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/EnvironmentPropertySourceTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/EnvironmentPropertySourceTest.java @@ -18,14 +18,16 @@ */ package org.apache.tamaya.spisupport.propertysource; -import org.apache.tamaya.spisupport.propertysource.EnvironmentPropertySource; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; import org.apache.tamaya.spi.PropertyValue; import org.junit.Test; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; +import org.junit.Ignore; /** * Tests for {@link EnvironmentPropertySource}. @@ -34,9 +36,59 @@ public class EnvironmentPropertySourceTest { private final EnvironmentPropertySource envPropertySource = new EnvironmentPropertySource(); + @Test + public void testConstructionPropertiesAndDisabledBehavior() throws IOException { + EnvironmentPropertySource localEnvironmentPropertySource; + StringWriter stringBufferWriter = new StringWriter(); + System.getProperties().store(stringBufferWriter, null); + String before = stringBufferWriter.toString(); + + try { + assertFalse(envPropertySource.isDisabled()); + + System.setProperty("tamaya.envprops.prefix", "fakeprefix"); + System.setProperty("tamaya.envprops.disable", "true"); + localEnvironmentPropertySource = new EnvironmentPropertySource(); + //assertEquals("fakeprefix", environmentSource.getPrefix()); + assertTrue(localEnvironmentPropertySource.isDisabled()); + assertNull(localEnvironmentPropertySource.get(System.getenv().entrySet().iterator().next().getKey())); + assertTrue(localEnvironmentPropertySource.getName().contains("(disabled)")); + assertTrue(localEnvironmentPropertySource.getProperties().isEmpty()); + assertTrue(localEnvironmentPropertySource.toString().contains("disabled=true")); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.defaults.disable", "true"); + localEnvironmentPropertySource = new EnvironmentPropertySource(); + assertTrue(localEnvironmentPropertySource.isDisabled()); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.envprops.disable", ""); + localEnvironmentPropertySource = new EnvironmentPropertySource(); + assertFalse(localEnvironmentPropertySource.isDisabled()); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.defaults.disable", ""); + localEnvironmentPropertySource = new EnvironmentPropertySource(); + assertFalse(localEnvironmentPropertySource.isDisabled()); + + } finally { + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + } + } + @Test public void testGetOrdinal() throws Exception { assertEquals(EnvironmentPropertySource.DEFAULT_ORDINAL, envPropertySource.getOrdinal()); + EnvironmentPropertySource constructorSetOrdinal22 = new EnvironmentPropertySource(22); + assertEquals(22, constructorSetOrdinal22.getOrdinal()); + + EnvironmentPropertySource constructorSetOrdinal16 = new EnvironmentPropertySource("sixteenprefix", 16); + assertEquals(16, constructorSetOrdinal16.getOrdinal()); + } @Test @@ -50,19 +102,48 @@ public void testGet() throws Exception { assertEquals(envPropertySource.get(envEntry.getKey()).getValue(), envEntry.getValue()); } } + + @Ignore + @Test + public void testPrefixedGet() throws Exception { + EnvironmentPropertySource localEnvironmentPropertySource = new EnvironmentPropertySource("fancyprefix"); + localEnvironmentPropertySource.setPropertiesProvider(new MockedSystemPropertiesProvider()); + assertEquals("fancyprefix.somekey.value", localEnvironmentPropertySource.get("somekey").getValue()); + } @Test public void testGetProperties() throws Exception { Map props = envPropertySource.getProperties(); - for(Map.Entry en: props.entrySet()){ - if(!en.getKey().startsWith("_")){ + for (Map.Entry en : props.entrySet()) { + if (!en.getKey().startsWith("_")) { assertEquals(System.getenv(en.getKey()), en.getValue().getValue()); } } } + @Test + public void testPrefixedGetProperties() throws Exception { + EnvironmentPropertySource localEnvironmentPropertySource = new EnvironmentPropertySource("someprefix"); + Map props = localEnvironmentPropertySource.getProperties(); + for (Map.Entry en : props.entrySet()) { + assertTrue(en.getKey().startsWith("someprefix")); + String thisKey = en.getKey().replaceFirst("someprefix", ""); + if (!thisKey.startsWith("_")) { + assertEquals(System.getenv(thisKey), en.getValue().getValue()); + } + } + } + @Test public void testIsScannable() throws Exception { assertTrue(envPropertySource.isScannable()); } -} \ No newline at end of file + + private class MockedSystemPropertiesProvider extends EnvironmentPropertySource.SystemPropertiesProvider { + @Override + String getenv(String key) { + System.out.println("Called with key " + key); + return key + ".value"; + } + } +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/JavaConfigurationProviderTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/JavaConfigurationProviderTest.java index 0e363b929..18c9df51d 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/JavaConfigurationProviderTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/JavaConfigurationProviderTest.java @@ -18,12 +18,17 @@ */ package org.apache.tamaya.spisupport.propertysource; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; import org.apache.tamaya.spi.PropertySource; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; -import static org.apache.tamaya.ConfigurationProvider.getConfiguration; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; public class JavaConfigurationProviderTest { @@ -43,4 +48,44 @@ public void loadsSimpleAndXMLPropertyFilesProper() { } } + + @Test + public void testConstructionPropertiesAndDisabledBehavior() throws IOException { + JavaConfigurationPropertySource localJavaConfigurationPropertySource = new JavaConfigurationPropertySource(); + StringWriter stringBufferWriter = new StringWriter(); + System.getProperties().store(stringBufferWriter, null); + String before = stringBufferWriter.toString(); + + try { + assertTrue(localJavaConfigurationPropertySource.isEnabled()); + + System.setProperty("tamaya.defaultprops.disable", "true"); + localJavaConfigurationPropertySource = new JavaConfigurationPropertySource(); + assertFalse(localJavaConfigurationPropertySource.isEnabled()); + assertTrue(localJavaConfigurationPropertySource.getProperties().isEmpty()); + assertTrue(localJavaConfigurationPropertySource.toString().contains("enabled=false")); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.defaults.disable", "true"); + localJavaConfigurationPropertySource = new JavaConfigurationPropertySource(); + assertFalse(localJavaConfigurationPropertySource.isEnabled()); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.defaultprops.disable", ""); + localJavaConfigurationPropertySource = new JavaConfigurationPropertySource(); + assertTrue(localJavaConfigurationPropertySource.isEnabled()); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.defaults.disable", ""); + localJavaConfigurationPropertySource = new JavaConfigurationPropertySource(); + assertTrue(localJavaConfigurationPropertySource.isEnabled()); + + } finally { + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + } + } } diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/PropertiesResourcePropertySourceTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/PropertiesResourcePropertySourceTest.java new file mode 100644 index 000000000..577576852 --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/PropertiesResourcePropertySourceTest.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport.propertysource; + +import java.net.URL; +import org.junit.Test; +import static org.junit.Assert.*; + + +/** + * + * @author William.Lieurance 2018.02.17 + */ +public class PropertiesResourcePropertySourceTest { + + private final String testFileName = "testfile.properties"; + private final URL resource = getClass().getResource("/" + testFileName); + + @Test + public void testBasicConstructor() { + PropertiesResourcePropertySource source = new PropertiesResourcePropertySource(resource); + assertNotNull(source); + assertTrue(5 == source.getProperties().size()); // double the size for .source values. + assertTrue(source.getProperties().containsKey("key1")); + } + + @Test + public void testPrefixedConstructor() { + PropertiesResourcePropertySource source = new PropertiesResourcePropertySource(resource, "somePrefix"); + assertNotNull(source); + assertTrue(5 == source.getProperties().size()); + assertTrue(source.getProperties().containsKey("somePrefixkey1")); + } + + @Test + public void testPrefixedPathConstructor() { + //File path must be relative to classloader, not the class + System.out.println(resource.getPath()); + PropertiesResourcePropertySource source = new PropertiesResourcePropertySource(testFileName, "somePrefix"); + assertNotNull(source); + assertTrue(5 == source.getProperties().size()); + assertTrue(source.getProperties().containsKey("somePrefixkey1")); + } + + @Test + public void testPrefixedPathBadClassloaderConstructor() { + ClassLoader badLoader = new ClassLoader() { + @Override + public URL getResource(String name){ + return null; + } + }; + PropertiesResourcePropertySource source = new PropertiesResourcePropertySource(testFileName, "somePrefix", badLoader); + assertNotNull(source); + assertTrue(source.getProperties().isEmpty()); + } + + @Test + public void testPrefixedPathClassloaderConstructor() { + PropertiesResourcePropertySource source = new PropertiesResourcePropertySource(testFileName, "somePrefix", null); + assertNotNull(source); + assertTrue(5 == source.getProperties().size()); + assertTrue(source.getProperties().containsKey("somePrefixkey1")); + } + +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/SimplePropertySourceTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/SimplePropertySourceTest.java index 288b8cdc4..5ceb332d3 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/SimplePropertySourceTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/SimplePropertySourceTest.java @@ -18,11 +18,15 @@ */ package org.apache.tamaya.spisupport.propertysource; +import java.io.File; import org.apache.tamaya.ConfigException; import org.apache.tamaya.spi.PropertyValue; import org.junit.Test; import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.endsWith; @@ -31,8 +35,13 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.aMapWithSize; import static org.hamcrest.Matchers.hasEntry; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class SimplePropertySourceTest { + @Test public void successfulCreationWithPropertiesFromXMLPropertiesFile() { URL resource = getClass().getResource("/valid-properties.xml"); @@ -58,7 +67,7 @@ public void failsToCreateFromNonXMLPropertiesXMLFile() { } assertThat(catchedException.getMessage(), allOf(startsWith("Error loading properties from"), - endsWith("non-xml-properties.xml"))); + endsWith("non-xml-properties.xml"))); } @Test @@ -73,10 +82,9 @@ public void failsToCreateFromInvalidPropertiesXMLFile() { } assertThat(catchedException.getMessage(), allOf(startsWith("Error loading properties from"), - endsWith("invalid-properties.xml"))); + endsWith("invalid-properties.xml"))); } - @Test public void successfulCreationWithPropertiesFromSimplePropertiesFile() { URL resource = getClass().getResource("/testfile.properties"); @@ -86,4 +94,99 @@ public void successfulCreationWithPropertiesFromSimplePropertiesFile() { assertThat(source, notNullValue()); assertThat(source.getProperties(), aMapWithSize(5)); // double the size for .source values. } + + @Test + public void testWithMap() { + Map propertyFirst = new HashMap<>(); + propertyFirst.put("firstKey", "firstValue"); + + SimplePropertySource source = new SimplePropertySource("testWithMap", propertyFirst, 166); + assertEquals("testWithMap", source.getName()); + assertEquals(166, source.getDefaultOrdinal()); + assertTrue(source.getProperties().containsKey("firstKey")); + + } + + @Test + public void builder() throws Exception { + assertNotNull(SimplePropertySource.newBuilder()); + assertNotEquals(SimplePropertySource.newBuilder(), SimplePropertySource.newBuilder()); + } + + @Test + public void getOrdinal() throws Exception { + SimplePropertySource ps1 = SimplePropertySource.newBuilder() + .withUuidName() + .withOrdinal(55) + .withDefaultOrdinal(166) + .build(); + + assertEquals(55, ps1.getOrdinal()); + assertEquals(166, ps1.getDefaultOrdinal()); + } + + @Test + public void getName() throws Exception { + //SimplePropertySource ps1 = SimplePropertySource.newBuilder() + // .withName("test1") + // .build(); + //assertEquals("test1", ps1.getName()); + SimplePropertySource ps1 = SimplePropertySource.newBuilder() + .withUuidName().build(); + assertNotNull(UUID.fromString(ps1.getName())); + } + + @Test + public void get() throws Exception { + SimplePropertySource ps1 = SimplePropertySource.newBuilder() + .withUuidName() + .withProperty("a", "b").build(); + assertEquals("b", ps1.get("a").getValue()); + } + + @Test + public void getProperties() throws Exception { + SimplePropertySource ps1 = SimplePropertySource.newBuilder() + .withUuidName() + .withProperty("a", "b") + .build(); + assertNotNull(ps1.getProperties()); + assertEquals(1, ps1.getProperties().size()); + assertEquals("b", ps1.getProperties().get("a").getValue()); + } + + @Test + public void testScannable() { + SimplePropertySource sps = SimplePropertySource.newBuilder().withUuidName().build(); + assertTrue(sps.isScannable()); + } + + @Test + public void testBuilderWithMaps() { + URL resource = getClass().getResource("/valid-properties.xml"); + File resourceAsFile = new File(resource.getPath()); + + Map propertyFirst = new HashMap<>(); + propertyFirst.put("firstKey", "firstValue"); + + SimplePropertySource sps = SimplePropertySource.newBuilder() + .withUuidName() + .withProperties(propertyFirst) + .withProperties(resource) + .build(); + + assertEquals("firstValue", sps.get("firstKey").getValue()); + assertThat(sps.getProperties(), hasEntry("a", PropertyValue.of("a", "b", resource.toString()))); + assertThat(sps.getProperties(), hasEntry("b", PropertyValue.of("b", "1", resource.toString()))); + + sps = SimplePropertySource.newBuilder() + .withUuidName() + .withProperties(propertyFirst) + .withProperties(resourceAsFile) + .build(); + + assertEquals("firstValue", sps.get("firstKey").getValue()); + assertThat(sps.getProperties(), hasEntry("a", PropertyValue.of("a", "b", resource.toString()))); + assertThat(sps.getProperties(), hasEntry("b", PropertyValue.of("b", "1", resource.toString()))); + } } diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/SystemPropertySourceTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/SystemPropertySourceTest.java index e67630cf3..acac8ea48 100644 --- a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/SystemPropertySourceTest.java +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/SystemPropertySourceTest.java @@ -18,6 +18,9 @@ */ package org.apache.tamaya.spisupport.propertysource; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; import org.apache.tamaya.spi.PropertySource; import org.apache.tamaya.spi.PropertyValue; import org.junit.Assert; @@ -25,11 +28,58 @@ import java.util.Map; import java.util.Properties; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; public class SystemPropertySourceTest { private final SystemPropertySource testPropertySource = new SystemPropertySource(); + @Test + public void testConstructionPropertiesAndDisabledBehavior() throws IOException { + SystemPropertySource localSystemPropertySource; + StringWriter stringBufferWriter = new StringWriter(); + System.getProperties().store(stringBufferWriter, null); + String before = stringBufferWriter.toString(); + + try { + assertFalse(testPropertySource.toStringValues().contains("disabled=true")); + + System.setProperty("tamaya.sysprops.prefix", "fakeprefix"); + System.setProperty("tamaya.sysprops.disable", "true"); + localSystemPropertySource = new SystemPropertySource(); + //assertEquals("fakeprefix", localSystemPropertySource.getPrefix()); + assertTrue(localSystemPropertySource.toStringValues().contains("disabled=true")); + assertNull(localSystemPropertySource.get(System.getenv().entrySet().iterator().next().getKey())); + assertTrue(localSystemPropertySource.getName().contains("(disabled)")); + assertTrue(localSystemPropertySource.getProperties().isEmpty()); + assertTrue(localSystemPropertySource.toString().contains("disabled=true")); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.defaults.disable", "true"); + localSystemPropertySource = new SystemPropertySource(); + assertTrue(localSystemPropertySource.toStringValues().contains("disabled=true")); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.sysprops.disable", ""); + localSystemPropertySource = new SystemPropertySource(); + assertFalse(localSystemPropertySource.toStringValues().contains("disabled=true")); + + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + System.setProperty("tamaya.defaults.disable", ""); + localSystemPropertySource = new SystemPropertySource(); + assertFalse(localSystemPropertySource.toStringValues().contains("disabled=true")); + + } finally { + System.getProperties().clear(); + System.getProperties().load(new StringReader(before)); + } + } @Test public void testGetOrdinal() throws Exception { @@ -44,6 +94,17 @@ public void testGetOrdinal() throws Exception { // reset it to not destroy other tests!! System.clearProperty(PropertySource.TAMAYA_ORDINAL); + + SystemPropertySource constructorSetOrdinal22 = new SystemPropertySource(22); + assertEquals(22, constructorSetOrdinal22.getOrdinal()); + + SystemPropertySource constructorSetOrdinal16 = new SystemPropertySource("sixteenprefix", 16); + assertEquals(16, constructorSetOrdinal16.getOrdinal()); + } + + @Test + public void testIsScannable() throws Exception { + assertTrue(testPropertySource.isScannable()); } @Test @@ -56,8 +117,8 @@ public void testGet() throws Exception { String propertyKeyToCheck = System.getProperties().stringPropertyNames().iterator().next(); PropertyValue property = testPropertySource.get(propertyKeyToCheck); - Assert.assertNotNull("Property '" + propertyKeyToCheck + "' is not present in " + - SystemPropertySource.class.getSimpleName(), property); + Assert.assertNotNull("Property '" + propertyKeyToCheck + "' is not present in " + + SystemPropertySource.class.getSimpleName(), property); Assert.assertEquals(System.getProperty(propertyKeyToCheck), property.getValue()); } @@ -74,18 +135,18 @@ public void testGetProperties() throws Exception { System.clearProperty("test"); } - private void checkWithSystemProperties(Map toCheck) { + private void checkWithSystemProperties(Map toCheck) { Properties systemEntries = System.getProperties(); int num = 0; for (PropertyValue propertySourceEntry : toCheck.values()) { - if(propertySourceEntry.getKey().startsWith("_")){ + if (propertySourceEntry.getKey().startsWith("_")) { continue; // meta entry } - num ++; + num++; Assert.assertEquals("Entry values for key '" + propertySourceEntry.getKey() + "' do not match", - systemEntries.getProperty(propertySourceEntry.getKey()), propertySourceEntry.getValue()); + systemEntries.getProperty(propertySourceEntry.getKey()), propertySourceEntry.getValue()); } Assert.assertEquals("size of System.getProperties().entrySet() must be the same as SystemPropertySrouce.getProperties().entrySet()", systemEntries.size(), num); } -} \ No newline at end of file +} diff --git a/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySourceTest.java b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySourceTest.java new file mode 100644 index 000000000..5b46ee71f --- /dev/null +++ b/code/spi-support/src/test/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySourceTest.java @@ -0,0 +1,168 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.spisupport.propertysource; + +import java.util.HashMap; +import java.util.Map; +import org.apache.tamaya.spi.PropertySource; +import org.apache.tamaya.spi.PropertyValue; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author William.Lieurance 2018.02.17 + */ +public class WrappedPropertySourceTest { + + /** + * Test of of method, of class WrappedPropertySource. + */ + @Test + public void testOf_PropertySource() { + WrappedPropertySource instance = WrappedPropertySource.of(new MockedWrappablePropertySource()); + assertEquals("MockedWrappablePropertySource", instance.getName()); + WrappedPropertySource instance2 = WrappedPropertySource.of(instance); + assertEquals("MockedWrappablePropertySource", instance2.getName()); + } + + /** + * Test of getOrdinal method, of class WrappedPropertySource. + */ + @Test + public void testOrdinalsAndOrdinalConstructors() { + WrappedPropertySource instance = WrappedPropertySource.of(new MockedWrappablePropertySource(), null); + assertEquals(10, instance.getOrdinal()); + instance.setOrdinal(20); + assertEquals(20, instance.getOrdinal()); + + WrappedPropertySource instance2 = WrappedPropertySource.of(instance, null); + assertEquals(10, instance2.getOrdinal()); + } + + /** + * Test of setDelegate method, of class WrappedPropertySource. + */ + @Test + public void testGetSetDelegate() { + MockedWrappablePropertySource first = new MockedWrappablePropertySource(); + first.setName("first"); + MockedWrappablePropertySource second = new MockedWrappablePropertySource(); + first.setName("second"); + + WrappedPropertySource instance = WrappedPropertySource.of(first); + assertEquals(first, instance.getDelegate()); + instance.setDelegate(second); + assertEquals(second, instance.getDelegate()); + + } + + + /** + * Test of get method, of class WrappedPropertySource. + */ + @Test + public void testGet() { + WrappedPropertySource instance = WrappedPropertySource.of(new MockedWrappablePropertySource()); + PropertyValue result = instance.get("thisKey"); + assertEquals("valueFromMockedWrappablePropertySource", result.getValue()); + } + + /** + * Test of getProperties method, of class WrappedPropertySource. + */ + @Test + public void testGetProperties() { + WrappedPropertySource instance = WrappedPropertySource.of(new MockedWrappablePropertySource()); + Map result = instance.getProperties(); + assertTrue(result.containsKey("someKey")); + assertEquals(1, result.size()); + } + + /** + * Test of isScannable method, of class WrappedPropertySource. + */ + @Test + public void testIsScannable() { + WrappedPropertySource instance = WrappedPropertySource.of(new MockedWrappablePropertySource()); + assertTrue(instance.isScannable()); + } + + @Test + public void testEqualsAndHashAndToStringValues() { + MockedWrappablePropertySource source1 = new MockedWrappablePropertySource(); + source1.setName("testEqualsName"); + MockedWrappablePropertySource source2 = new MockedWrappablePropertySource(); + source2.setName("testEqualsName"); + MockedWrappablePropertySource source3 = new MockedWrappablePropertySource(); + source3.setName("testNotEqualsName"); + + WrappedPropertySource wps1 = WrappedPropertySource.of(source1); + WrappedPropertySource wps2 = WrappedPropertySource.of(source2); + WrappedPropertySource wps3 = WrappedPropertySource.of(source3); + + assertEquals(wps1, wps1); + assertNotEquals(null, wps1); + assertNotEquals(source1, wps1); + assertNotEquals(wps1, source1); + assertNotEquals("aString", wps1); + assertEquals(wps1, wps2); + assertNotEquals(wps1, wps3); + assertEquals(wps1.hashCode(), wps2.hashCode()); + assertNotEquals(wps1.hashCode(), wps3.hashCode()); + assertTrue(wps1.toString().contains("name=testEqualsName")); + } + + private class MockedWrappablePropertySource implements PropertySource{ + + private String name = "MockedWrappablePropertySource"; + + @Override + public int getOrdinal() { + return 10; + } + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public PropertyValue get(String key) { + return PropertyValue.of(key, "valueFromMockedWrappablePropertySource", "MockedWrappablePropertySource"); + } + + @Override + public Map getProperties() { + Map returnable = new HashMap<>(); + returnable.put("someKey", this.get("someKey")); + return returnable; + } + + @Override + public boolean isScannable(){ + return true; + } + + } +} diff --git a/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertyConverter b/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertyConverter index 7c62bb21e..65a3dfeaf 100644 --- a/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertyConverter +++ b/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertyConverter @@ -16,4 +16,5 @@ # specific language governing permissions and limitations # under the License. # -org.apache.tamaya.spisupport.CTestConverter \ No newline at end of file +org.apache.tamaya.spisupport.CTestConverter +org.apache.tamaya.spisupport.IntegerTestConverter diff --git a/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter b/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter new file mode 100644 index 000000000..2e5456d75 --- /dev/null +++ b/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter @@ -0,0 +1,19 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy current the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +org.apache.tamaya.spisupport.MockedPropertyFilter diff --git a/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource b/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource new file mode 100644 index 000000000..06799ddbe --- /dev/null +++ b/code/spi-support/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource @@ -0,0 +1,19 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy current the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +org.apache.tamaya.spisupport.MockedPropertySource