DATAGEODE-34 - Add EnableClusterConfiguration annotation to push cluster configuration meta-data from the client to the server.

This commit is contained in:
John Blum
2017-08-05 21:43:56 -07:00
parent 52c29de30e
commit 51caf48973
55 changed files with 6129 additions and 107 deletions

View File

@@ -0,0 +1,290 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.admin;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.Index;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.config.schema.SchemaObjectDefinition;
import org.springframework.data.gemfire.config.schema.SchemaObjectType;
import org.springframework.data.gemfire.config.schema.definitions.IndexDefinition;
import org.springframework.data.gemfire.config.schema.definitions.RegionDefinition;
/**
* The GemfireAdminOperationsUnitTests class...
*
* @author John Blum
* @since 1.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class GemfireAdminOperationsUnitTests {
@Mock
private GemfireAdminOperations adminOperations;
private Index mockIndex(String name) {
Index mockIndex = mock(Index.class, name);
when(mockIndex.getName()).thenReturn(name);
return mockIndex;
}
@SuppressWarnings("unchecked")
private <K, V> Region<K, V> mockRegion(String name) {
Region<K, V> mockRegion = mock(Region.class, name);
when(mockRegion.getName()).thenReturn(name);
return mockRegion;
}
private SchemaObjectDefinition newGenericSchemaObjectDefinition(String name, SchemaObjectType type) {
return mock(SchemaObjectDefinition.class, name);
}
@Test
public void createRegionsWithArrayCallsCreateRegion() {
doCallRealMethod().when(adminOperations).createRegions(ArgumentMatchers.<RegionDefinition[]>any());
RegionDefinition definitionOne = RegionDefinition.from(mockRegion("RegionOne"));
RegionDefinition definitionTwo = RegionDefinition.from(mockRegion("RegionTwo"));
adminOperations.createRegions(definitionOne, definitionTwo);
verify(adminOperations, times(1)).createRegion(eq(definitionOne));
verify(adminOperations, times(1)).createRegion(eq(definitionTwo));
}
@Test
public void createRegionsWithEmptyArray() {
doCallRealMethod().when(adminOperations).createRegions(ArgumentMatchers.<RegionDefinition[]>any());
adminOperations.createRegions();
verify(adminOperations, never()).createRegion(any(RegionDefinition.class));
}
@Test
public void createRegionsWithNullArray() {
doCallRealMethod().when(adminOperations).createRegions(ArgumentMatchers.<RegionDefinition[]>any());
adminOperations.createRegions((RegionDefinition[]) null);
verify(adminOperations, never()).createRegion(any(RegionDefinition.class));
}
@Test
@SuppressWarnings("unchecked")
public void createRegionsWithIterableCallsCreateRegion() {
doCallRealMethod().when(adminOperations).createRegions(any(Iterable.class));
RegionDefinition definitionOne = RegionDefinition.from(mockRegion("RegionOne"));
RegionDefinition definitionTwo = RegionDefinition.from(mockRegion("RegionTwo"));
adminOperations.createRegions(Arrays.asList(definitionOne, definitionTwo));
verify(adminOperations, times(1)).createRegion(eq(definitionOne));
verify(adminOperations, times(1)).createRegion(eq(definitionTwo));
}
@Test
@SuppressWarnings("unchecked")
public void createRegionsWithEmptyIterableCallsCreateRegion() {
doCallRealMethod().when(adminOperations).createRegions(any(Iterable.class));
adminOperations.createRegions(Collections.emptyList());
verify(adminOperations, never()).createRegion(any(RegionDefinition.class));
}
@Test
@SuppressWarnings("unchecked")
public void createRegionsWithNullIterableCallsCreateRegion() {
adminOperations.createRegions((Iterable) null);
verify(adminOperations, never()).createRegion(any(RegionDefinition.class));
}
@Test
public void createLuceneIndexesWithArrayCallsCreateLuceneIndex() {
doCallRealMethod().when(adminOperations).createLuceneIndexes(ArgumentMatchers.<SchemaObjectDefinition[]>any());
SchemaObjectDefinition definitionOne = newGenericSchemaObjectDefinition("LucenIndexOne",
SchemaObjectType.LUCENE_INDEX);
SchemaObjectDefinition definitionTwo = newGenericSchemaObjectDefinition("LucenIndexOne",
SchemaObjectType.LUCENE_INDEX);
adminOperations.createLuceneIndexes(definitionOne, definitionTwo);
verify(adminOperations, times(1)).createLuceneIndex(eq(definitionOne));
verify(adminOperations, times(1)).createLuceneIndex(eq(definitionTwo));
}
@Test
public void createLuceneIndexesWithEmptyArray() {
doCallRealMethod().when(adminOperations).createLuceneIndexes(ArgumentMatchers.<SchemaObjectDefinition[]>any());
adminOperations.createLuceneIndexes();
verify(adminOperations, never()).createLuceneIndex(any(SchemaObjectDefinition.class));
}
@Test
public void createLuceneIndexesWithNullArray() {
doCallRealMethod().when(adminOperations).createLuceneIndexes(ArgumentMatchers.<SchemaObjectDefinition[]>any());
adminOperations.createLuceneIndexes((SchemaObjectDefinition) null);
verify(adminOperations, never()).createLuceneIndex(any(SchemaObjectDefinition.class));
}
@Test
@SuppressWarnings("unchecked")
public void createLuceneIndexesWithIterableCallsCreateLuceneIndex() {
doCallRealMethod().when(adminOperations).createLuceneIndexes(any(Iterable.class));
SchemaObjectDefinition definitionOne = newGenericSchemaObjectDefinition("LucenIndexOne",
SchemaObjectType.LUCENE_INDEX);
SchemaObjectDefinition definitionTwo = newGenericSchemaObjectDefinition("LucenIndexOne",
SchemaObjectType.LUCENE_INDEX);
adminOperations.createLuceneIndexes(Arrays.asList(definitionOne, definitionTwo));
verify(adminOperations, times(1)).createLuceneIndex(eq(definitionOne));
verify(adminOperations, times(1)).createLuceneIndex(eq(definitionTwo));
}
@Test
@SuppressWarnings("unchecked")
public void createLuceneIndexesWithEmptyIterableCallsCreateLuceneIndex() {
doCallRealMethod().when(adminOperations).createLuceneIndexes(any(Iterable.class));
adminOperations.createLuceneIndexes(Collections.emptyList());
verify(adminOperations, never()).createLuceneIndex(any(SchemaObjectDefinition.class));
}
@Test
@SuppressWarnings("unchecked")
public void createLuceneIndexesWithNullIterableCallsCreateLuceneIndex() {
adminOperations.createLuceneIndexes((Iterable) null);
verify(adminOperations, never()).createLuceneIndex(any(SchemaObjectDefinition.class));
}
@Test
public void createIndexesWithArrayCallsCreateIndex() {
doCallRealMethod().when(adminOperations).createIndexes(ArgumentMatchers.<IndexDefinition[]>any());
IndexDefinition definitionOne = IndexDefinition.from(mockIndex("IndexOne"));
IndexDefinition definitionTwo = IndexDefinition.from(mockIndex("IndexTwo"));
adminOperations.createIndexes(definitionOne, definitionTwo);
verify(adminOperations, times(1)).createIndex(eq(definitionOne));
verify(adminOperations, times(1)).createIndex(eq(definitionTwo));
}
@Test
public void createIndexesWithEmptyArray() {
doCallRealMethod().when(adminOperations).createIndexes(ArgumentMatchers.<IndexDefinition[]>any());
adminOperations.createIndexes();
verify(adminOperations, never()).createIndex(any(IndexDefinition.class));
}
@Test
public void createIndexesWithNullArray() {
doCallRealMethod().when(adminOperations).createIndexes(ArgumentMatchers.<IndexDefinition[]>any());
adminOperations.createIndexes();
verify(adminOperations, never()).createIndex(any(IndexDefinition.class));
}
@Test
@SuppressWarnings("unchecked")
public void createIndexesWithIterableCallsCreateIndex() {
doCallRealMethod().when(adminOperations).createIndexes(any(Iterable.class));
IndexDefinition definitionOne = IndexDefinition.from(mockIndex("IndexOne"));
IndexDefinition definitionTwo = IndexDefinition.from(mockIndex("IndexTwo"));
adminOperations.createIndexes(Arrays.asList(definitionOne, definitionTwo));
verify(adminOperations, times(1)).createIndex(eq(definitionOne));
verify(adminOperations, times(1)).createIndex(eq(definitionTwo));
}
@Test
@SuppressWarnings("unchecked")
public void createIndexesWithEmptyIterable() {
doCallRealMethod().when(adminOperations).createIndexes(any(Iterable.class));
adminOperations.createIndexes(Collections.emptyList());
verify(adminOperations, never()).createIndex(any(IndexDefinition.class));
}
@Test
@SuppressWarnings("unchecked")
public void createIndexesWithNullIterable() {
adminOperations.createIndexes((Iterable) null);
verify(adminOperations, never()).createIndex(any(IndexDefinition.class));
}
}

View File

@@ -0,0 +1,156 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.admin.functions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collections;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.query.Index;
import org.apache.geode.cache.query.QueryException;
import org.apache.geode.cache.query.QueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.IndexType;
import org.springframework.data.gemfire.config.schema.definitions.IndexDefinition;
/**
* Unit tests for {@link CreateIndexFunction}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.apache.geode.cache.Cache
* @see org.apache.geode.cache.query.Index
* @see org.apache.geode.cache.query.QueryService
* @see org.springframework.data.gemfire.config.schema.definitions.IndexDefinition
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class CreateIndexFunctionUnitTests {
@Mock
private Cache mockCache;
private CreateIndexFunction createIndexFunction;
@Mock
private Index mockIndex;
@Mock
private QueryService mockQueryService;
@Before
public void setup() {
this.createIndexFunction = spy(new CreateIndexFunction());
doReturn(this.mockCache).when(this.createIndexFunction).resolveCache();
when(this.mockCache.getQueryService()).thenReturn(this.mockQueryService);
when(this.mockIndex.getName()).thenReturn("MockIndex");
}
@Test
public void createsFunctionalIndex() throws QueryException {
when(this.mockIndex.getIndexedExpression()).thenReturn("age");
when(this.mockIndex.getFromClause()).thenReturn("/Customers");
when(this.mockIndex.getType()).thenReturn(IndexType.FUNCTIONAL.getGemfireIndexType());
when(this.mockQueryService.getIndexes()).thenReturn(null);
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(this.createIndexFunction.createIndex(indexDefinition)).isTrue();
verify(this.mockCache, times(2)).getQueryService();
verify(this.mockQueryService, times(1)).getIndexes();
verify(this.mockQueryService, times(1))
.createIndex(eq("MockIndex"), eq("age"), eq("/Customers"));
}
@Test
public void createsHashIndex() throws QueryException {
Index mockIndexTwo = mock(Index.class, "MockIndexTwo");
when(mockIndexTwo.getName()).thenReturn("MockIndexTwo");
when(this.mockIndex.getIndexedExpression()).thenReturn("name");
when(this.mockIndex.getFromClause()).thenReturn("/Customers");
when(this.mockIndex.getType()).thenReturn(IndexType.HASH.getGemfireIndexType());
when(this.mockQueryService.getIndexes()).thenReturn(Collections.singleton(mockIndexTwo));
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(this.createIndexFunction.createIndex(indexDefinition)).isTrue();
verify(this.mockCache, times(2)).getQueryService();
verify(this.mockQueryService, times(1)).getIndexes();
verify(mockIndexTwo, times(1)).getName();
verify(this.mockQueryService, times(1))
.createHashIndex(eq("MockIndex"), eq("name"), eq("/Customers"));
}
@Test
public void createsKeyIndex() throws QueryException {
when(this.mockIndex.getIndexedExpression()).thenReturn("id");
when(this.mockIndex.getFromClause()).thenReturn("/Customers");
when(this.mockIndex.getType()).thenReturn(IndexType.PRIMARY_KEY.getGemfireIndexType());
when(this.mockQueryService.getIndexes()).thenReturn(Collections.emptyList());
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(this.createIndexFunction.createIndex(indexDefinition)).isTrue();
verify(this.mockCache, times(2)).getQueryService();
verify(this.mockQueryService, times(1)).getIndexes();
verify(this.mockQueryService, times(1))
.createKeyIndex(eq("MockIndex"), eq("id"), eq("/Customers"));
}
@Test
public void doesNotCreateIndexWhenIndexAlreadyExists() throws QueryException {
when(this.mockQueryService.getIndexes()).thenReturn(Collections.singleton(this.mockIndex));
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(this.createIndexFunction.createIndex(indexDefinition)).isFalse();
verify(this.mockCache, times(1)).getQueryService();
verify(this.mockQueryService, times(1)).getIndexes();
verify(this.mockQueryService, never()).createIndex(anyString(), anyString(), anyString());
verify(this.mockQueryService, never()).createIndex(anyString(), anyString(), anyString(), anyString());
verify(this.mockQueryService, never()).createHashIndex(anyString(), anyString(), anyString());
verify(this.mockQueryService, never()).createHashIndex(anyString(), anyString(), anyString(), anyString());
verify(this.mockQueryService, never()).createKeyIndex(anyString(), anyString(), anyString());
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.admin.functions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.config.schema.definitions.RegionDefinition;
/**
* Unit tests for {@link CreateRegionFunction}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.apache.geode.cache.Cache
* @see org.apache.geode.cache.Region
* @see org.springframework.data.gemfire.config.schema.definitions.RegionDefinition
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class CreateRegionFunctionUnitTests {
@Mock
private Cache mockCache;
@Mock
private Region<Object, Object> mockRegion;
private CreateRegionFunction createRegionFunction;
@Before
public void setup() {
this.createRegionFunction = spy(new CreateRegionFunction());
doReturn(this.mockCache).when(this.createRegionFunction).resolveCache();
when(this.mockRegion.getName()).thenReturn("MockRegion");
}
@Test
@SuppressWarnings("unchecked")
public void createsRegionWhenRegionDoesNotExist() {
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion);
RegionFactory<Object, Object> mockRegionFactory = mock(RegionFactory.class);
when(this.mockCache.getRegion(anyString())).thenReturn(null);
when(this.mockCache.createRegionFactory(any(RegionShortcut.class))).thenReturn(mockRegionFactory);
assertThat(this.createRegionFunction.createRegion(regionDefinition)).isTrue();
verify(this.mockCache, times(1)).getRegion(eq("MockRegion"));
verify(this.mockCache, times(1)).createRegionFactory(eq(RegionShortcut.PARTITION));
verify(mockRegionFactory, times(1)).create(eq("MockRegion"));
}
@Test
public void doesNotCreateRegionWhenRegionAlreadyExists() {
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion);
when(this.mockCache.getRegion(anyString())).thenReturn(this.mockRegion);
assertThat(this.createRegionFunction.createRegion(regionDefinition)).isFalse();
verify(this.mockCache, times(1)).getRegion(eq("MockRegion"));
verify(this.mockCache, never()).createRegionFactory();
}
}

View File

@@ -0,0 +1,124 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.admin.functions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.query.Index;
import org.apache.geode.cache.query.QueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Unit tests for {@link ListIndexesFunction}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.apache.geode.cache.Cache
* @see org.apache.geode.cache.query.Index
* @see org.apache.geode.cache.query.QueryService
* @see org.springframework.data.gemfire.config.admin.functions.ListIndexesFunction
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class ListIndexesFunctionUnitTests {
@Mock
private Cache mockCache;
@Mock
private Index mockIndexOne;
@Mock
private Index mockIndexTwo;
private ListIndexesFunction listIndexesFunction;
@Mock
private QueryService mockQueryService;
@Before
public void setup() {
this.listIndexesFunction = spy(new ListIndexesFunction());
doReturn(this.mockCache).when(this.listIndexesFunction).resolveCache();
when(this.mockCache.getQueryService()).thenReturn(this.mockQueryService);
when(this.mockIndexOne.getName()).thenReturn("MockIndexOne");
when(this.mockIndexTwo.getName()).thenReturn("MockIndexTwo");
}
@Test
public void listIndexesReturnsIndexNames() {
when(this.mockQueryService.getIndexes()).thenReturn(Arrays.asList(this.mockIndexOne, this.mockIndexTwo));
assertThat(this.listIndexesFunction.listIndexes()).contains("MockIndexOne", "MockIndexTwo");
verify(this.listIndexesFunction, times(1)).resolveCache();
verify(this.mockCache, times(1)).getQueryService();
verify(this.mockQueryService, times(1)).getIndexes();
verify(this.mockIndexOne, times(1)).getName();
verify(this.mockIndexTwo, times(1)).getName();
}
@Test
public void listIndexesReturnsEmptySetWhenCacheIsNull() {
doReturn(null).when(this.listIndexesFunction).resolveCache();
assertThat(this.listIndexesFunction.listIndexes()).isEmpty();
verify(this.listIndexesFunction, times(1)).resolveCache();
}
@Test
public void listIndexesReturnsEmptySetWhenQueryServiceIsNull() {
when(this.mockCache.getQueryService()).thenReturn(null);
assertThat(this.listIndexesFunction.listIndexes()).isEmpty();
verify(this.listIndexesFunction, times(1)).resolveCache();
verify(this.mockCache, times(1)).getQueryService();
}
@Test
public void listIndexesReturnsEmptySetWhenQueryServiceGetIndexesIsNull() {
when(this.mockQueryService.getIndexes()).thenReturn(null);
assertThat(this.listIndexesFunction.listIndexes()).isEmpty();
verify(this.listIndexesFunction, times(1)).resolveCache();
verify(this.mockCache, times(1)).getQueryService();
verify(this.mockQueryService, times(1)).getIndexes();
}
}

View File

@@ -0,0 +1,233 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.admin.remote;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.ArrayUtils.asArray;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.query.Index;
import org.apache.geode.management.internal.cli.domain.RegionInformation;
import org.apache.geode.management.internal.cli.functions.GetRegionsFunction;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.client.function.ListRegionsOnServerFunction;
import org.springframework.data.gemfire.config.admin.functions.CreateIndexFunction;
import org.springframework.data.gemfire.config.admin.functions.CreateRegionFunction;
import org.springframework.data.gemfire.config.admin.functions.ListIndexesFunction;
import org.springframework.data.gemfire.config.schema.definitions.IndexDefinition;
import org.springframework.data.gemfire.config.schema.definitions.RegionDefinition;
import org.springframework.data.gemfire.function.execution.GemfireFunctionOperations;
/**
* Unit tests for {@link FunctionGemfireAdminTemplate}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.config.admin.remote.FunctionGemfireAdminTemplate
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class FunctionGemfireAdminTemplateUnitTests {
private FunctionGemfireAdminTemplate template;
@Mock
private ClientCache mockClientCache;
@Mock
private GemfireFunctionOperations mockFunctionOperations;
@Mock
private Index mockIndex;
@Mock
private Region mockRegion;
@Before
public void setup() {
this.template = spy(new FunctionGemfireAdminTemplate(this.mockClientCache));
when(this.template.newGemfireFunctionOperations(any(ClientCache.class)))
.thenReturn(this.mockFunctionOperations);
when(this.mockIndex.getName()).thenReturn("MockIndex");
when(this.mockRegion.getName()).thenReturn("MockRegion");
}
private Region mockRegion(String name) {
Region mockRegion = mock(Region.class, name);
when(mockRegion.getFullPath()).thenReturn(String.format("%1$s%2$s", Region.SEPARATOR, name));
RegionAttributes mockRegionAttributes = mock(RegionAttributes.class,
String.format("Mock%sRegionAttributes", name));
when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PARTITION);
when(mockRegionAttributes.getScope()).thenReturn(Scope.DISTRIBUTED_ACK);
when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
return mockRegion;
}
private RegionInformation newRegionInformation(String regionName) {
return new RegionInformation(mockRegion(regionName), false);
}
@Test
public void constructFunctionGemfireAdminTemplateWithClientCache() {
FunctionGemfireAdminTemplate template = new FunctionGemfireAdminTemplate(this.mockClientCache);
assertThat(template).isNotNull();
assertThat(template.getClientCache()).isSameAs(this.mockClientCache);
}
@Test(expected = IllegalArgumentException.class)
public void constructFunctionGemfireAdminTemplateWithNull() {
try {
new FunctionGemfireAdminTemplate(null);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("ClientCache is required");
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test
public void getAvailableServerRegionsExecutesListRegionsOnServerFunction() {
when(this.mockFunctionOperations.executeAndExtract(any(Function.class)))
.thenReturn(asSet("RegionOne", "RegionTwo"));
Iterable<String> availableServerRegions = this.template.getAvailableServerRegions();
assertThat(availableServerRegions).isNotNull();
assertThat(availableServerRegions).hasSize(2);
assertThat(availableServerRegions).contains("RegionOne", "RegionTwo");
verify(this.mockFunctionOperations, times(1))
.executeAndExtract(isA(ListRegionsOnServerFunction.class));
}
@Test
public void getAvailableServerRegionsExecutesGetRegionsFunction() {
when(this.mockFunctionOperations.executeAndExtract(isA(ListRegionsOnServerFunction.class)))
.thenThrow(new RuntimeException("TEST"));
Object[] regionInformation = asArray(newRegionInformation("MockRegionOne"),
newRegionInformation("MockRegionTwo"));
when(this.mockFunctionOperations.executeAndExtract(isA(GetRegionsFunction.class)))
.thenReturn(regionInformation);
Iterable<String> availableServerRegions = this.template.getAvailableServerRegions();
assertThat(availableServerRegions).isNotNull();
assertThat(availableServerRegions).hasSize(2);
assertThat(availableServerRegions).contains("MockRegionOne", "MockRegionTwo");
verify(this.mockFunctionOperations, times(1))
.executeAndExtract(isA(ListRegionsOnServerFunction.class));
verify(this.mockFunctionOperations, times(1))
.executeAndExtract(isA(GetRegionsFunction.class));
}
@Test
public void getAvailableServerRegionIndexesCallsExecuteWithListIndexesFunctionId() {
this.template.getAvailableServerRegionIndexes();
verify(this.mockFunctionOperations, times(1))
.executeAndExtract(eq(ListIndexesFunction.LIST_INDEXES_FUNCTION_ID));
}
@Test
public void createRegionCallsExecuteWithCreateRegionFunctionIdAndRegionDefinition() {
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion);
this.template.createRegion(regionDefinition);
verify(this.mockFunctionOperations, times(1))
.executeAndExtract(eq(CreateRegionFunction.CREATE_REGION_FUNCTION_ID), eq(regionDefinition));
}
@Test
public void createIndexCallsExecuteWithCreateIndexFunctionIdAndIndexDefinition() {
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
this.template.createIndex(indexDefinition);
verify(this.mockFunctionOperations, times(1))
.executeAndExtract(eq(CreateIndexFunction.CREATE_INDEX_FUNCTION_ID), eq(indexDefinition));
}
@Test
public void containsRegionInformationIsNullSafe() {
assertThat(this.template.containsRegionInformation(null)).isFalse();
}
@Test
public void containsRegionInformationReturnsFalseForNonObjectArrayResult() {
assertThat(this.template.containsRegionInformation(newRegionInformation("TestRegion"))).isFalse();
}
@Test
public void containsRegionInformationReturnsFalseForEmptyObjectArrayResult() {
assertThat(this.template.containsRegionInformation(asArray())).isFalse();
}
@Test
public void containsRegionInformationReturnsFalseForObjectArrayContainingNonRegionInformation() {
assertThat(this.template.containsRegionInformation(asArray(mockRegion("TestRegion")))).isFalse();
}
@Test
public void containsRegionInformationReturnsTrueForObjectArrayWithRegionInformation() {
assertThat(this.template.containsRegionInformation(asArray(newRegionInformation("TestRegion"))))
.isTrue();
}
}

View File

@@ -0,0 +1,195 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.admin.remote;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.net.URI;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.query.Index;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.IndexType;
import org.springframework.data.gemfire.config.schema.definitions.IndexDefinition;
import org.springframework.data.gemfire.config.schema.definitions.RegionDefinition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestOperations;
/**
* Unit tests for {@link RestHttpGemfireAdminTemplate}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.config.admin.remote.RestHttpGemfireAdminTemplate
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class RestHttpGemfireAdminTemplateUnitTests {
@Mock
private ClientCache mockClientCache;
@Mock
private Index mockIndex;
@Mock
private Region mockRegion;
private RestHttpGemfireAdminTemplate template;
@Mock
private RestOperations mockRestOperations;
@Before
public void setup() {
this.template = new RestHttpGemfireAdminTemplate(this.mockClientCache) {
@Override protected RestOperations newRestOperations() {
return mockRestOperations;
}
};
when(this.mockRegion.getName()).thenReturn("MockRegion");
when(this.mockIndex.getName()).thenReturn("MockIndex");
when(this.mockIndex.getIndexedExpression()).thenReturn("age");
when(this.mockIndex.getFromClause()).thenReturn("/Customers");
when(this.mockIndex.getType()).thenReturn(IndexType.FUNCTIONAL.getGemfireIndexType());
}
@Test
public void constructDefaultRestHttpGemfireAdminTemplate() {
RestHttpGemfireAdminTemplate template = new RestHttpGemfireAdminTemplate(this.mockClientCache);
assertThat(template).isNotNull();
assertThat(template.getClientCache()).isSameAs(this.mockClientCache);
assertThat(template.getManagementRestApiUrl())
.isEqualTo(String.format(RestHttpGemfireAdminTemplate.MANAGEMENT_REST_API_URL_TEMPLATE,
RestHttpGemfireAdminTemplate.DEFAULT_HOST, RestHttpGemfireAdminTemplate.DEFAULT_PORT));
assertThat(template.getRestOperations()).isNotNull();
}
@Test
public void constructCustomRestHttpGemfireAdminTemplate() {
RestHttpGemfireAdminTemplate template =
new RestHttpGemfireAdminTemplate(this.mockClientCache, "skullbox", 8080);
assertThat(template).isNotNull();
assertThat(template.getClientCache()).isSameAs(this.mockClientCache);
assertThat(template.getManagementRestApiUrl())
.isEqualTo(String.format(RestHttpGemfireAdminTemplate.MANAGEMENT_REST_API_URL_TEMPLATE, "skullbox", 8080));
assertThat(template.getRestOperations()).isNotNull();
}
@Test
@SuppressWarnings("unchecked")
public void createIndexCallsGemFireManagementRestApi() {
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
when(this.mockRestOperations.exchange(any(RequestEntity.class), eq(String.class))).thenAnswer(invocation -> {
RequestEntity requestEntity = invocation.getArgument(0);
assertThat(requestEntity).isNotNull();
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl()).isEqualTo(URI.create("http://localhost:7070/gemfire/v1/indexes"));
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers).isNotNull();
assertThat(headers.getContentType()).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED);
Object body = requestEntity.getBody();
assertThat(body).isInstanceOf(MultiValueMap.class);
MultiValueMap<String, Object> requestBody = (MultiValueMap<String, Object>) body;
assertThat(requestBody.getFirst("name")).isEqualTo(indexDefinition.getName());
assertThat(requestBody.getFirst("expression")).isEqualTo(indexDefinition.getExpression());
assertThat(requestBody.getFirst("region")).isEqualTo(indexDefinition.getFromClause());
assertThat(requestBody.getFirst("type")).isEqualTo(indexDefinition.getIndexType().toString());
return new ResponseEntity(HttpStatus.OK);
});
this.template.createIndex(indexDefinition);
verify(this.mockRestOperations, times(1))
.exchange(isA(RequestEntity.class), eq(String.class));
}
@Test
@SuppressWarnings("unchecked")
public void createRegionCallsGemFireManagementRestApi() {
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion);
when(this.mockRestOperations.exchange(any(RequestEntity.class), eq(String.class))).thenAnswer(invocation -> {
RequestEntity requestEntity = invocation.getArgument(0);
assertThat(requestEntity).isNotNull();
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl()).isEqualTo(URI.create("http://localhost:7070/gemfire/v1/regions"));
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers).isNotNull();
assertThat(headers.getContentType()).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED);
Object body = requestEntity.getBody();
assertThat(body).isInstanceOf(MultiValueMap.class);
MultiValueMap<String, Object> requestBody = (MultiValueMap<String, Object>) body;
assertThat(requestBody.getFirst("name")).isEqualTo(regionDefinition.getName());
assertThat(requestBody.getFirst("type")).isEqualTo(regionDefinition.getRegionShortcut().toString());
assertThat(requestBody.getFirst("skip-if-exists"))
.isEqualTo(String.valueOf(RestHttpGemfireAdminTemplate.CREATE_REGION_SKIP_IF_EXISTS_DEFAULT));
return new ResponseEntity(HttpStatus.OK);
});
this.template.createRegion(regionDefinition);
verify(this.mockRestOperations, times(1))
.exchange(isA(RequestEntity.class), eq(String.class));
}
}

View File

@@ -0,0 +1,267 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.annotation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collections;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Import;
import org.springframework.data.gemfire.IndexFactoryBean;
import org.springframework.data.gemfire.IndexType;
import org.springframework.data.gemfire.PartitionedRegionFactoryBean;
import org.springframework.data.gemfire.ReplicatedRegionFactoryBean;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
import org.springframework.data.gemfire.config.admin.GemfireAdminOperations;
import org.springframework.data.gemfire.config.admin.functions.CreateIndexFunction;
import org.springframework.data.gemfire.config.admin.functions.CreateRegionFunction;
import org.springframework.data.gemfire.config.admin.functions.ListIndexesFunction;
import org.springframework.data.gemfire.config.admin.remote.RestHttpGemfireAdminTemplate;
import org.springframework.data.gemfire.function.config.EnableGemfireFunctions;
import org.springframework.data.gemfire.process.ProcessWrapper;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.test.support.ClientServerIntegrationTestsSupport;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration tests for the {@link EnableClusterConfiguration} annotation
* and {@link ClusterConfigurationConfiguration} class.
*
* @author John Blum
* @see org.junit.Test
* @see org.springframework.context.annotation.Bean
* @see org.springframework.context.annotation.Configuration
* @see org.springframework.context.annotation.Import
* @see org.springframework.data.gemfire.IndexFactoryBean
* @see org.springframework.data.gemfire.client.ClientRegionFactoryBean
* @see org.springframework.data.gemfire.config.admin.GemfireAdminOperations
* @see org.springframework.data.gemfire.config.annotation.ClusterConfigurationConfiguration
* @see org.springframework.data.gemfire.config.annotation.EnableClusterConfiguration
* @see org.springframework.data.gemfire.process.ProcessWrapper
* @see org.springframework.data.gemfire.test.support.ClientServerIntegrationTestsSupport
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringRunner
* @since 2.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = EnableClusterConfigurationIntegrationTests.TestConfiguration.class)
@SuppressWarnings("unused")
public class EnableClusterConfigurationIntegrationTests extends ClientServerIntegrationTestsSupport {
private static final String LOG_LEVEL = "warning";
private static ProcessWrapper gemfireServer;
@Autowired
private ClientCache gemfireCache;
private GemfireAdminOperations adminOperations;
@BeforeClass
public static void startGemFireServer() throws Exception {
int availablePort = findAvailablePort();
gemfireServer = run(GemFireServerConfiguration.class,
String.format("-D%s=%d", GEMFIRE_CACHE_SERVER_PORT_PROPERTY, availablePort));
waitForServerToStart("localhost", availablePort);
System.setProperty(GEMFIRE_CACHE_SERVER_PORT_PROPERTY, String.valueOf(availablePort));
}
@AfterClass
public static void stopGemFireServer() {
System.clearProperty(GEMFIRE_CACHE_SERVER_PORT_PROPERTY);
stop(gemfireServer);
}
@Before
public void setup() {
this.adminOperations = new RestHttpGemfireAdminTemplate(this.gemfireCache,
"localhost", Integer.getInteger(GEMFIRE_CACHE_SERVER_PORT_PROPERTY, 40404));
}
@Test
public void serverIndexesAreCorrect() {
assertThat(this.adminOperations.getAvailableServerRegionIndexes())
.containsAll(Arrays.asList("IndexOne", "IndexTwo"));
}
@Test
public void serverRegionsAreCorrect() {
assertThat(this.adminOperations.getAvailableServerRegions())
.containsAll(Arrays.asList("RegionOne", "RegionTwo", "RegionThree", "RegionFour"));
}
@Configuration
@EnableClusterConfiguration
@Import(GemFireClientConfiguration.class)
static class TestConfiguration {
}
@ClientCacheApplication(logLevel = LOG_LEVEL, subscriptionEnabled = true)
static class GemFireClientConfiguration {
@Bean
ClientCacheConfigurer clientCachePoolPortConfigurer(
@Value("${" + GEMFIRE_CACHE_SERVER_PORT_PROPERTY + ":40404}") int port) {
return (bean, clientCacheFactoryBean) -> clientCacheFactoryBean.setServers(
Collections.singletonList(new ConnectionEndpoint("localhost", port)));
}
@Bean("IndexOne")
@DependsOn("RegionOne")
IndexFactoryBean indexOne(GemFireCache gemfireCache) {
IndexFactoryBean indexFactory = new IndexFactoryBean();
indexFactory.setCache(gemfireCache);
indexFactory.setExpression("id");
indexFactory.setFrom("/RegionOne");
indexFactory.setType(IndexType.KEY);
return indexFactory;
}
@Bean("RegionOne")
ClientRegionFactoryBean<Object, Object> regionOne(GemFireCache gemfireCache) {
ClientRegionFactoryBean<Object, Object> clientRegionFactory = new ClientRegionFactoryBean<>();
clientRegionFactory.setCache(gemfireCache);
clientRegionFactory.setClose(false);
clientRegionFactory.setShortcut(ClientRegionShortcut.PROXY);
return clientRegionFactory;
}
@Bean("RegionTwo")
ClientRegionFactoryBean<Object, Object> regionTwo(GemFireCache gemfireCache) {
ClientRegionFactoryBean<Object, Object> clientRegionFactory = new ClientRegionFactoryBean<>();
clientRegionFactory.setCache(gemfireCache);
clientRegionFactory.setClose(false);
clientRegionFactory.setShortcut(ClientRegionShortcut.PROXY);
return clientRegionFactory;
}
@Bean("RegionThree")
ClientRegionFactoryBean<Object, Object> regionThree(GemFireCache gemfireCache) {
ClientRegionFactoryBean<Object, Object> clientRegionFactory = new ClientRegionFactoryBean<>();
clientRegionFactory.setCache(gemfireCache);
clientRegionFactory.setClose(false);
clientRegionFactory.setShortcut(ClientRegionShortcut.CACHING_PROXY);
return clientRegionFactory;
}
}
@CacheServerApplication(name = "EnableClusterConfigurationIntegrationTests", logLevel = LOG_LEVEL)
@EnableGemfireFunctions
static class GemFireServerConfiguration {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
EnableClusterConfigurationIntegrationTests.GemFireServerConfiguration.class);
applicationContext.registerShutdownHook();
}
@Bean
CreateIndexFunction createIndexFunction() {
return new CreateIndexFunction();
}
@Bean
CreateRegionFunction createRegionFunction() {
return new CreateRegionFunction();
}
@Bean
ListIndexesFunction listIndexesFunction() {
return new ListIndexesFunction();
}
@Bean
CacheServerConfigurer cacheServerPortConfigurer(
@Value("${" + GEMFIRE_CACHE_SERVER_PORT_PROPERTY + ":40404}") int port) {
return (bean, cacheServerFactoryBean) -> cacheServerFactoryBean.setPort(port);
}
@Bean("IndexTwo")
@DependsOn("RegionTwo")
IndexFactoryBean indexTwo(GemFireCache gemfireCache) {
IndexFactoryBean indexFactory = new IndexFactoryBean();
indexFactory.setCache(gemfireCache);
indexFactory.setExpression("name");
indexFactory.setFrom("/RegionTwo");
indexFactory.setType(IndexType.HASH);
return indexFactory;
}
@Bean("RegionTwo")
PartitionedRegionFactoryBean<Object, Object> regionTwo(GemFireCache gemfireCache) {
PartitionedRegionFactoryBean<Object, Object> regionFactoryBean = new PartitionedRegionFactoryBean<>();
regionFactoryBean.setCache(gemfireCache);
regionFactoryBean.setClose(false);
regionFactoryBean.setPersistent(false);
return regionFactoryBean;
}
@Bean("RegionFour")
ReplicatedRegionFactoryBean<Object, Object> regionFour(GemFireCache gemfireCache) {
ReplicatedRegionFactoryBean<Object, Object> regionFactoryBean = new ReplicatedRegionFactoryBean<>();
regionFactoryBean.setCache(gemfireCache);
regionFactoryBean.setClose(false);
regionFactoryBean.setPersistent(false);
return regionFactoryBean;
}
}
}

View File

@@ -0,0 +1,153 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.core.Ordered;
/**
* Unit tests for {@link SchemaObjectDefinition}.
*
* @author John Blum
* @see org.junit.Test
* @see org.springframework.data.gemfire.config.schema.SchemaObjectDefinition
* @since 2.0.0
*/
public class SchemaObjectDefinitionUnitTests {
private SchemaObjectDefinition newSchemaObjectDefinition(String name) {
return new TestSchemaObjectDefinition(name);
}
@Test
public void constructSchemaObjectDefinitionWithName() {
SchemaObjectDefinition schemaObjectDefinition = newSchemaObjectDefinition("TEST");
assertThat(schemaObjectDefinition).isNotNull();
assertThat(schemaObjectDefinition.getName()).isEqualTo("TEST");
assertThat(schemaObjectDefinition.getType()).isEqualTo(SchemaObjectType.UNKNOWN);
}
private SchemaObjectDefinition testConstructSchemaObjectDefinitionWithInvalidName(String name) {
try {
return newSchemaObjectDefinition(name);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Name [%s] is required", name);
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test(expected = IllegalArgumentException.class)
public void constructSchemaObjectDefinitionWithNull() {
testConstructSchemaObjectDefinitionWithInvalidName(null);
}
@Test(expected = IllegalArgumentException.class)
public void constructSchemaObjectDefinitionWithNoName() {
testConstructSchemaObjectDefinitionWithInvalidName(" ");
}
@Test(expected = IllegalArgumentException.class)
public void constructSchemaObjectDefinitionWithEmptyName() {
testConstructSchemaObjectDefinitionWithInvalidName("");
}
@Test
public void equalSchemaObjectDefinitionsAreEqual() {
SchemaObjectDefinition schemaObjectDefinitionOne = newSchemaObjectDefinition("TEST");
SchemaObjectDefinition schemaObjectDefinitionTwo = newSchemaObjectDefinition("TEST");
assertThat(schemaObjectDefinitionOne).isNotSameAs(schemaObjectDefinitionTwo);
assertThat(schemaObjectDefinitionOne).isEqualTo(schemaObjectDefinitionTwo);
}
@Test
public void identicalSchemaObjectDefinitionsAreEquals() {
SchemaObjectDefinition schemaObjectDefinition = newSchemaObjectDefinition("TEST");
assertThat(schemaObjectDefinition).isEqualTo(schemaObjectDefinition);
}
@Test
public void unequalSchemaObjectDefinitionsAreNotEqual() {
SchemaObjectDefinition schemaObjectDefinitionOne = newSchemaObjectDefinition("TEST");
SchemaObjectDefinition schemaObjectDefinitionTwo = newSchemaObjectDefinition("test");
assertThat(schemaObjectDefinitionOne).isNotSameAs(schemaObjectDefinitionTwo);
assertThat(schemaObjectDefinitionOne).isNotEqualTo(schemaObjectDefinitionTwo);
}
@Test
public void equalSchemaObjectDefinitionsHaveTheSameHashCode() {
SchemaObjectDefinition schemaObjectDefinitionOne = newSchemaObjectDefinition("TEST");
SchemaObjectDefinition schemaObjectDefinitionTwo = newSchemaObjectDefinition("TEST");
assertThat(schemaObjectDefinitionOne).isNotSameAs(schemaObjectDefinitionTwo);
assertThat(schemaObjectDefinitionOne.hashCode()).isEqualTo(schemaObjectDefinitionTwo.hashCode());
}
@Test
public void identicalSchemaObjectDefinitionsHaveTheSameHashCode() {
SchemaObjectDefinition schemaObjectDefinition = newSchemaObjectDefinition("TEST");
assertThat(schemaObjectDefinition.hashCode()).isEqualTo(schemaObjectDefinition.hashCode());
}
@Test
public void unequalSchemaObjectDefinitionsHaveDifferentHashCodes() {
SchemaObjectDefinition schemaObjectDefinitionOne = newSchemaObjectDefinition("TEST");
SchemaObjectDefinition schemaObjectDefinitionTwo = newSchemaObjectDefinition("test");
assertThat(schemaObjectDefinitionOne).isNotSameAs(schemaObjectDefinitionTwo);
assertThat(schemaObjectDefinitionOne.hashCode()).isNotEqualTo(schemaObjectDefinitionTwo.hashCode());
}
@Test
public void toStringPrintsNameAndType() {
assertThat(newSchemaObjectDefinition("test").toString()).isEqualTo("UNKNOWN[test]");
}
private static final class TestSchemaObjectDefinition extends SchemaObjectDefinition {
private TestSchemaObjectDefinition(String name) {
super(name);
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public SchemaObjectType getType() {
return SchemaObjectType.UNKNOWN;
}
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema;
import static java.util.Arrays.stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.asyncqueue.AsyncEventQueue;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.lucene.LuceneIndex;
import org.apache.geode.cache.query.Index;
import org.apache.geode.cache.wan.GatewayReceiver;
import org.apache.geode.cache.wan.GatewaySender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Unit tests for {@link SchemaObjectType}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.config.schema.SchemaObjectType
* @since 1.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class SchemaObjectTypeUnitTests {
@Test
public void objectTypesAreSetAndCorrect() {
Set<Class<?>> expectedSchemaObjectTypes = asSet(AsyncEventQueue.class, Cache.class, ClientCache.class,
DiskStore.class, Function.class, GatewayReceiver.class, GatewaySender.class, Index.class, LuceneIndex.class,
Pool.class, Region.class, Void.class);
Set<Class<?>> actualSchemaObjectTypes = stream(SchemaObjectType.values())
.map(SchemaObjectType::getObjectType)
.collect(Collectors.toSet());
assertThat(actualSchemaObjectTypes).hasSameSizeAs(expectedSchemaObjectTypes);
assertThat(actualSchemaObjectTypes).containsAll(expectedSchemaObjectTypes);
}
@Test
public void fromClass() {
stream(SchemaObjectType.values()).forEach(it ->
assertThat(SchemaObjectType.from(it.getObjectType())).isSameAs(it));
}
@Test
public void fromNullIsUnknown() {
assertThat(SchemaObjectType.from(null)).isSameAs(SchemaObjectType.UNKNOWN);
assertThat(SchemaObjectType.from((Object) null)).isSameAs(SchemaObjectType.UNKNOWN);
}
@Test
public void fromObject() {
stream(SchemaObjectType.values()).filter(it -> !SchemaObjectType.UNKNOWN.equals(it)).forEach(it ->
assertThat(SchemaObjectType.from(mock(it.getObjectType()))).isSameAs(it));
}
@Test
public void fromUntypedObjectIsUnknown() {
assertThat(SchemaObjectType.from(new Object())).isSameAs(SchemaObjectType.UNKNOWN);
}
}

View File

@@ -0,0 +1,316 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.definitions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.Index;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.IndexType;
import org.springframework.data.gemfire.config.admin.GemfireAdminOperations;
import org.springframework.data.gemfire.config.schema.SchemaObjectType;
import org.springframework.data.gemfire.test.support.IOUtils;
/**
* Unit tests for {@link IndexDefinition}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.apache.geode.cache.Region
* @see org.apache.geode.cache.query.Index
* @see org.springframework.data.gemfire.IndexType
* @see org.springframework.data.gemfire.config.schema.definitions.IndexDefinition
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class IndexDefinitionUnitTests {
@Mock
private Index mockIndex;
@Mock
private Region<?, ?> mockRegion;
@Before
public void setup() {
when(this.mockIndex.getName()).thenReturn("MockIndex");
when(this.mockRegion.getFullPath()).thenReturn(String.format("%sMockRegion", Region.SEPARATOR));
}
private Index mockIndex(String name, String expression, String fromClause, IndexType type) {
Index mockIndex = mock(Index.class);
when(mockIndex.getName()).thenReturn(name);
when(mockIndex.getIndexedExpression()).thenReturn(expression);
when(mockIndex.getFromClause()).thenReturn(fromClause);
when(mockIndex.getType()).thenReturn(type.getGemfireIndexType());
return mockIndex;
}
@Test
public void fromIndexCreatesAnIndexDefinition() {
Index mockIndex = mockIndex("TestIndex", "id", "/Customers", IndexType.PRIMARY_KEY);
IndexDefinition indexDefinition = IndexDefinition.from(mockIndex);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getExpression()).isEqualTo(mockIndex.getIndexedExpression());
assertThat(indexDefinition.getFromClause()).isEqualTo(mockIndex.getFromClause());
assertThat(indexDefinition.getIndex()).isSameAs(mockIndex);
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.valueOf(mockIndex.getType()));
assertThat(indexDefinition.getType()).isEqualTo(SchemaObjectType.INDEX);
}
@Test(expected = IllegalArgumentException.class)
public void fromNullIndexThrowsIllegalArgumentException() {
try {
IndexDefinition.from(null);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Index is required");
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test
public void createCallsGemfireAdminOperationsCreateIndexWithThis() {
GemfireAdminOperations mockAdminOperations = mock(GemfireAdminOperations.class);
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getIndex()).isSameAs(this.mockIndex);
indexDefinition.create(mockAdminOperations);
verify(mockAdminOperations, times(1)).createIndex(eq(indexDefinition));
}
@Test
@SuppressWarnings("deprecation")
public void asDifferentIndexTypes() {
when(this.mockIndex.getType()).thenReturn(IndexType.FUNCTIONAL.getGemfireIndexType());
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getIndex()).isSameAs(this.mockIndex);
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.FUNCTIONAL);
assertThat(indexDefinition.as(IndexType.HASH)).isSameAs(indexDefinition);
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.HASH);
assertThat(indexDefinition.as(org.apache.geode.cache.query.IndexType.PRIMARY_KEY)).isSameAs(indexDefinition);
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.PRIMARY_KEY);
}
@Test
public void asNullIndexType() {
when(this.mockIndex.getType()).thenReturn(IndexType.FUNCTIONAL.getGemfireIndexType());
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getIndex()).isSameAs(this.mockIndex);
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.FUNCTIONAL);
assertThat(indexDefinition.as((IndexType) null)).isSameAs(indexDefinition);
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.FUNCTIONAL);
assertThat(indexDefinition.as(IndexType.HASH)).isSameAs(indexDefinition);
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.HASH);
assertThat(indexDefinition.as((IndexType) null)).isSameAs(indexDefinition);
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.FUNCTIONAL);
}
private void testHavingIllegalExpression(String expression) {
try {
IndexDefinition.from(this.mockIndex).having(expression);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Expression is required");
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test
public void havingExpression() {
when(this.mockIndex.getIndexedExpression()).thenReturn("id");
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getIndex()).isSameAs(this.mockIndex);
assertThat(indexDefinition.getExpression()).isEqualTo("id");
assertThat(indexDefinition.having("age")).isSameAs(indexDefinition);
assertThat(indexDefinition.getExpression()).isEqualTo("age");
}
@Test(expected = IllegalArgumentException.class)
public void havingEmptyExpression() {
testHavingIllegalExpression("");
}
@Test(expected = IllegalArgumentException.class)
public void havingNoExpression() {
testHavingIllegalExpression(" ");
}
@Test(expected = IllegalArgumentException.class)
public void havingNullExpression() {
testHavingIllegalExpression(null);
}
private void testOnIllegalFromClause(String fromClause) {
try {
IndexDefinition.from(this.mockIndex).on(fromClause);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("From Clause is required");
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test
public void onFromClause() {
when(this.mockIndex.getFromClause()).thenReturn("/People");
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getFromClause()).isEqualTo(this.mockIndex.getFromClause());
assertThat(indexDefinition.on("/Customers")).isSameAs(indexDefinition);
assertThat(indexDefinition.getFromClause()).isEqualTo("/Customers");
}
@Test(expected = IllegalArgumentException.class)
public void onEmptyFromClause() {
testOnIllegalFromClause("");
}
@Test(expected = IllegalArgumentException.class)
public void onNoFromClause() {
testOnIllegalFromClause(" ");
}
@Test(expected = IllegalArgumentException.class)
public void onNullFromClause() {
testOnIllegalFromClause(null);
}
@Test
public void onRegion() {
when(this.mockIndex.getFromClause()).thenReturn("/Mock");
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getFromClause()).isEqualTo(this.mockIndex.getFromClause());
assertThat(indexDefinition.on(this.mockRegion)).isSameAs(indexDefinition);
assertThat(indexDefinition.getFromClause()).isEqualTo(this.mockRegion.getFullPath());
}
@Test(expected = IllegalArgumentException.class)
public void onNullRegion() {
try {
IndexDefinition.from(this.mockIndex).on((Region) null);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Region is required");
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test
public void withName() {
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getName()).isEqualTo("MockIndex");
assertThat(indexDefinition.with("TestIndex")).isSameAs(indexDefinition);
assertThat(indexDefinition.getName()).isEqualTo("TestIndex");
assertThat(indexDefinition.with("")).isSameAs(indexDefinition);
assertThat(indexDefinition.getName()).isEqualTo("MockIndex");
assertThat(indexDefinition.with("UniqueIndex")).isSameAs(indexDefinition);
assertThat(indexDefinition.getName()).isEqualTo("UniqueIndex");
assertThat(indexDefinition.with(" ")).isSameAs(indexDefinition);
assertThat(indexDefinition.getName()).isEqualTo("MockIndex");
assertThat(indexDefinition.with("NonUniqueIndex")).isSameAs(indexDefinition);
assertThat(indexDefinition.getName()).isEqualTo("NonUniqueIndex");
assertThat(indexDefinition.with(null)).isSameAs(indexDefinition);
assertThat(indexDefinition.getName()).isEqualTo("MockIndex");
}
@Test
public void serializeDeserializeIsSuccessful() throws ClassNotFoundException, IOException {
when(this.mockIndex.getIndexedExpression()).thenReturn("age");
when(this.mockIndex.getFromClause()).thenReturn("/Customers");
when(this.mockIndex.getType()).thenReturn(IndexType.FUNCTIONAL.getGemfireIndexType());
IndexDefinition indexDefinition = IndexDefinition.from(this.mockIndex);
byte[] indexDefinitionBytes = IOUtils.serializeObject(indexDefinition);
IndexDefinition deserializedIndexDefinition = IOUtils.deserializeObject(indexDefinitionBytes);
assertThat(deserializedIndexDefinition).isNotNull();
assertThat(deserializedIndexDefinition).isNotSameAs(indexDefinition);
assertThat(deserializedIndexDefinition.getIndex()).isInstanceOf(Index.class);
assertThat(deserializedIndexDefinition.getIndex()).isNotSameAs(this.mockIndex);
assertThat(deserializedIndexDefinition.getName()).isEqualTo("MockIndex");
assertThat(deserializedIndexDefinition.getExpression()).isEqualTo("age");
assertThat(deserializedIndexDefinition.getFromClause()).isEqualTo("/Customers");
assertThat(deserializedIndexDefinition.getIndexType()).isEqualTo(IndexType.FUNCTIONAL);
}
}

View File

@@ -0,0 +1,151 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.definitions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionShortcut;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.config.admin.GemfireAdminOperations;
import org.springframework.data.gemfire.config.schema.SchemaObjectType;
import org.springframework.data.gemfire.test.support.IOUtils;
/**
* Unit tests for {@link RegionDefinition}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.config.schema.definitions.RegionDefinition
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class RegionDefinitionUnitTests {
@Mock
private Region<?, ?> mockRegion;
@Before
public void setup() {
assertThat(this.mockRegion).isNotNull();
when(this.mockRegion.getName()).thenReturn("MockRegion");
}
@Test
public void fromRegionCreatesRegionDefinition() {
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion);
assertThat(regionDefinition).isNotNull();
assertThat(regionDefinition.getName()).isEqualTo(this.mockRegion.getName());
assertThat(regionDefinition.getRegion()).isSameAs(this.mockRegion);
assertThat(regionDefinition.getRegionShortcut()).isEqualTo(RegionDefinition.DEFAULT_REGION_SHORTCUT);
assertThat(regionDefinition.getType()).isEqualTo(SchemaObjectType.REGION);
}
@Test(expected = IllegalArgumentException.class)
public void fromNullRegionThrowsIllegalArgumentException() {
try {
RegionDefinition.from(null);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Region is required");
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test
public void create() {
GemfireAdminOperations mockAdminOperations = mock(GemfireAdminOperations.class);
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion);
assertThat(regionDefinition).isNotNull();
assertThat(regionDefinition.getRegion()).isSameAs(this.mockRegion);
regionDefinition.create(mockAdminOperations);
verify(mockAdminOperations, times(1)).createRegion(eq(regionDefinition));
}
@Test
public void havingRegionShortcut() {
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion);
assertThat(regionDefinition).isNotNull();
assertThat(regionDefinition.getRegion()).isSameAs(this.mockRegion);
assertThat(regionDefinition.getRegionShortcut()).isEqualTo(RegionDefinition.DEFAULT_REGION_SHORTCUT);
assertThat(regionDefinition.having(RegionShortcut.LOCAL)).isSameAs(regionDefinition);
assertThat(regionDefinition.getRegionShortcut()).isEqualTo(RegionShortcut.LOCAL);
assertThat(regionDefinition.having(null)).isSameAs(regionDefinition);
assertThat(regionDefinition.getRegionShortcut()).isEqualTo(RegionDefinition.DEFAULT_REGION_SHORTCUT);
assertThat(regionDefinition.having(RegionShortcut.REPLICATE)).isSameAs(regionDefinition);
assertThat(regionDefinition.getRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE);
}
@Test
public void withName() {
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion);
assertThat(regionDefinition).isNotNull();
assertThat(regionDefinition.getRegion()).isSameAs(this.mockRegion);
assertThat(regionDefinition.getName()).isEqualTo(this.mockRegion.getName());
assertThat(regionDefinition.with("/Test")).isSameAs(regionDefinition);
assertThat(regionDefinition.getName()).isEqualTo("/Test");
assertThat(regionDefinition.with(" ")).isSameAs(regionDefinition);
assertThat(regionDefinition.getName()).isEqualTo(this.mockRegion.getName());
assertThat(regionDefinition.with("/Mock")).isSameAs(regionDefinition);
assertThat(regionDefinition.getName()).isEqualTo("/Mock");
assertThat(regionDefinition.with(null)).isSameAs(regionDefinition);
assertThat(regionDefinition.getName()).isEqualTo(this.mockRegion.getName());
}
@Test
public void serializeDeserializeIsSuccessful() throws IOException, ClassNotFoundException {
RegionDefinition regionDefinition = RegionDefinition.from(this.mockRegion).having(RegionShortcut.REPLICATE);
byte[] regionDefinitionBytes = IOUtils.serializeObject(regionDefinition);
RegionDefinition deserializedRegionDefinition = IOUtils.deserializeObject(regionDefinitionBytes);
assertThat(deserializedRegionDefinition).isNotNull();
assertThat(deserializedRegionDefinition.getRegion()).isNull();
assertThat(deserializedRegionDefinition.getName()).isEqualTo("MockRegion");
assertThat(deserializedRegionDefinition.getRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE);
}
}

View File

@@ -0,0 +1,151 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.support;
import static java.util.Arrays.stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationContext;
/**
* Unit tests for {@link ClientRegionCollector}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.config.schema.support.ClientRegionCollector
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class ClientRegionCollectorUnitTests {
@Mock
private ApplicationContext mockApplicationContext;
@Mock
private GemFireCache mockCache;
private ClientRegionCollector clientRegionCollector = new ClientRegionCollector();
@SuppressWarnings("unchecked")
private <K, V> Region<K, V> mockRegion(String name) {
Region<K, V> mockRegion = mock(Region.class, name);
when(mockRegion.getName()).thenReturn(name);
return mockRegion;
}
private Map<String, Region> asMap(Region<?, ?>... regions) {
return stream(regions).collect(Collectors.toMap(Region::getName, Function.identity()));
}
@Test
public void collectClientRegionsFromApplicationContext() {
Region mockRegionOne = mockRegion("MockRegionOne");
Region mockRegionTwo = mockRegion("MockRegionTwo");
Region mockRegionThree = mockRegion("MockRegionThree");
RegionAttributes mockRegionAttributes = mock(RegionAttributes.class);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
when(mockRegionTwo.getAttributes()).thenReturn(mockRegionAttributes);
Map<String, Region> regionBeans = asMap(mockRegionOne, mockRegionTwo, mockRegionThree);
when(this.mockApplicationContext.getBeansOfType(eq(Region.class))).thenReturn(regionBeans);
Set<Region> clientRegions = this.clientRegionCollector.collectFrom(this.mockApplicationContext);
assertThat(clientRegions).isNotNull();
assertThat(clientRegions).hasSize(1);
assertThat(clientRegions).containsAll(asSet(mockRegionTwo));
verify(this.mockApplicationContext, times(1)).getBeansOfType(eq(Region.class));
}
@Test
public void collectClientRegionsFromApplicationContextWithNoClientRegions() {
Region mockRegionOne = mockRegion("MockRegionOne");
Region mockRegionTwo = mockRegion("MockRegionTwo");
Region mockRegionThree = mockRegion("MockRegionThree");
RegionAttributes mockRegionAttributes = mock(RegionAttributes.class);
when(mockRegionAttributes.getPoolName()).thenReturn(" ");
when(mockRegionOne.getAttributes()).thenReturn(mockRegionAttributes);
when(mockRegionThree.getAttributes()).thenReturn(mockRegionAttributes);
Map<String, Region> regionBeans = asMap(mockRegionOne, mockRegionTwo, mockRegionThree);
when(this.mockApplicationContext.getBeansOfType(eq(Region.class))).thenReturn(regionBeans);
Set<Region> clientRegions = this.clientRegionCollector.collectFrom(this.mockApplicationContext);
assertThat(clientRegions).isNotNull();
assertThat(clientRegions).isEmpty();
verify(this.mockApplicationContext, times(1)).getBeansOfType(eq(Region.class));
}
@Test
@SuppressWarnings("unchecked")
public void collectClientRegionsFromGemFireCache() {
Region mockRegionOne = mockRegion("MockRegionOne");
Region mockRegionTwo = mockRegion("MockRegionTwo");
Region mockRegionThree = mockRegion("MockRegionThree");
RegionAttributes mockRegionAttributes = mock(RegionAttributes.class);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
when(mockRegionOne.getAttributes()).thenReturn(mockRegionAttributes);
when(mockRegionTwo.getAttributes()).thenReturn(mockRegionAttributes);
when(this.mockCache.rootRegions()).thenReturn(asSet(mockRegionOne, mockRegionTwo, mockRegionThree));
Set<Region> clientRegions = this.clientRegionCollector.collectFrom(this.mockCache);
assertThat(clientRegions).isNotNull();
assertThat(clientRegions).hasSize(2);
assertThat(clientRegions).containsAll(asSet(mockRegionOne, mockRegionTwo));
verify(this.mockCache, times(1)).rootRegions();
}
}

View File

@@ -0,0 +1,182 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Collections;
import org.apache.geode.cache.GemFireCache;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.data.gemfire.config.schema.SchemaObjectCollector;
import org.springframework.data.gemfire.config.schema.SchemaObjectType;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
/**
* Unit tests for {@link ComposableSchemaObjectCollector}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.config.schema.support.ComposableSchemaObjectCollector
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class ComposableSchemaObjectCollectorUnitTests {
@Mock
private ApplicationContext mockApplicationContext;
@Mock
private GemFireCache mockCache;
@Mock
private SchemaObjectCollector<Object> mockSchemaObjectCollectorOne;
@Mock
private SchemaObjectCollector<Object> mockSchemaObjectCollectorTwo;
private <T> Iterable<T> emptyIterable() {
return Collections::emptyIterator;
}
@Test
public void composeArrayWithNoElements() {
assertThat(ComposableSchemaObjectCollector.compose()).isNull();
}
@Test
public void composeArrayWithOneElement() {
assertThat(ComposableSchemaObjectCollector.compose(this.mockSchemaObjectCollectorOne))
.isSameAs(this.mockSchemaObjectCollectorOne);
}
@Test
public void composeArrayWithTwoElements() {
SchemaObjectCollector<?> composedSchemaObjectCollector = ComposableSchemaObjectCollector.compose(
this.mockSchemaObjectCollectorOne, this.mockSchemaObjectCollectorTwo);
assertThat(composedSchemaObjectCollector).isInstanceOf(ComposableSchemaObjectCollector.class);
assertThat((ComposableSchemaObjectCollector) composedSchemaObjectCollector).hasSize(2);
assertThat((ComposableSchemaObjectCollector) composedSchemaObjectCollector)
.containsAll(asSet(this.mockSchemaObjectCollectorOne, this.mockSchemaObjectCollectorTwo));
}
@Test
public void composeIterableWithNoElements() {
assertThat(ComposableSchemaObjectCollector.compose(emptyIterable())).isNull();
}
@Test
public void composableIterableWithOneElement() {
assertThat(ComposableSchemaObjectCollector.compose(Collections.singleton(this.mockSchemaObjectCollectorTwo)))
.isSameAs(this.mockSchemaObjectCollectorTwo);
}
@Test
public void composeIterableWithTwoElements() {
SchemaObjectCollector<?> composedSchemaObjectCollector = ComposableSchemaObjectCollector.compose(
asSet(this.mockSchemaObjectCollectorOne, this.mockSchemaObjectCollectorTwo));
assertThat(composedSchemaObjectCollector).isInstanceOf(ComposableSchemaObjectCollector.class);
assertThat((ComposableSchemaObjectCollector) composedSchemaObjectCollector)
.containsAll(asSet(this.mockSchemaObjectCollectorOne, this.mockSchemaObjectCollectorTwo));
}
@Test
@SuppressWarnings("unchecked")
public void collectFromApplicationContext() {
SchemaObject region = SchemaObject.of(SchemaObjectType.REGION);
SchemaObject index = SchemaObject.of(SchemaObjectType.INDEX);
SchemaObject diskStore = SchemaObject.of(SchemaObjectType.DISK_STORE);
when(this.mockSchemaObjectCollectorOne.collectFrom(any(ApplicationContext.class)))
.thenReturn(asSet(region, index));
when(this.mockSchemaObjectCollectorTwo.collectFrom(any(ApplicationContext.class)))
.thenReturn(asSet(diskStore));
SchemaObjectCollector composedSchemaObjectCollector = ComposableSchemaObjectCollector.compose(
asSet(this.mockSchemaObjectCollectorOne, this.mockSchemaObjectCollectorTwo));
assertThat(composedSchemaObjectCollector).isNotNull();
Iterable<Object> schemaObjects = composedSchemaObjectCollector.collectFrom(this.mockApplicationContext);
assertThat(schemaObjects).isNotNull();
assertThat(schemaObjects).hasSize(3);
assertThat(schemaObjects).contains(region, index, diskStore);
verify(this.mockSchemaObjectCollectorOne, times(1))
.collectFrom(eq(this.mockApplicationContext));
verify(this.mockSchemaObjectCollectorTwo, times(1))
.collectFrom(eq(this.mockApplicationContext));
}
@Test
@SuppressWarnings("unchecked")
public void collectFromGemFireCache() {
SchemaObject asyncEventQueue = SchemaObject.of(SchemaObjectType.ASYNC_EVENT_QUEUE);
SchemaObject gatewayReceiver = SchemaObject.of(SchemaObjectType.GATEWAY_RECEIVER);
SchemaObject gatewaySender = SchemaObject.of(SchemaObjectType.GATEWAY_SENDER);
when(this.mockSchemaObjectCollectorOne.collectFrom(any(GemFireCache.class)))
.thenReturn(asSet(gatewayReceiver, gatewaySender));
when(this.mockSchemaObjectCollectorTwo.collectFrom(any(GemFireCache.class)))
.thenReturn(asSet(asyncEventQueue));
SchemaObjectCollector composedSchemaObjectCollector = ComposableSchemaObjectCollector.compose(
asSet(this.mockSchemaObjectCollectorOne, this.mockSchemaObjectCollectorTwo));
assertThat(composedSchemaObjectCollector).isNotNull();
Iterable<Object> schemaObjects = composedSchemaObjectCollector.collectFrom(this.mockCache);
assertThat(schemaObjects).isNotNull();
assertThat(schemaObjects).hasSize(3);
assertThat(schemaObjects).contains(gatewayReceiver, gatewaySender, asyncEventQueue);
verify(this.mockSchemaObjectCollectorOne, times(1)).collectFrom(eq(this.mockCache));
verify(this.mockSchemaObjectCollectorTwo, times(1)).collectFrom(eq(this.mockCache));
}
@RequiredArgsConstructor(staticName = "of")
static class SchemaObject {
@NonNull SchemaObjectType type;
}
}

View File

@@ -0,0 +1,169 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
import org.apache.geode.cache.Region;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.config.schema.SchemaObjectDefiner;
import org.springframework.data.gemfire.config.schema.SchemaObjectType;
import org.springframework.data.gemfire.config.schema.definitions.RegionDefinition;
/**
* Unit tests for {@link ComposableSchemaObjectDefiner}.
*
* @author John Blum
* @see org.junit.Test
* @see SchemaObjectDefiner
* @see ComposableSchemaObjectDefiner
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class ComposableSchemaObjectDefinerUnitTests {
@Mock
private SchemaObjectDefiner mockHandlerOne;
@Mock
private SchemaObjectDefiner mockHandlerTwo;
private <T> Iterable<T> emptyIterable() {
return Collections::<T>emptyIterator;
}
@Test
public void composeArrayWithNoElements() {
assertThat(ComposableSchemaObjectDefiner.compose()).isNull();
}
@Test
public void composeArrayWithOneElement() {
assertThat(ComposableSchemaObjectDefiner.compose(this.mockHandlerOne)).isSameAs(this.mockHandlerOne);
}
@Test
public void composeArrayWithTwoElements() {
SchemaObjectDefiner handler =
ComposableSchemaObjectDefiner.compose(this.mockHandlerOne, this.mockHandlerTwo);
assertThat(handler).isInstanceOf(ComposableSchemaObjectDefiner.class);
assertThat((ComposableSchemaObjectDefiner) handler)
.containsAll(asSet(this.mockHandlerOne, this.mockHandlerTwo));
}
@Test
public void composeIterableWithNoElements() {
assertThat(ComposableSchemaObjectDefiner.compose(emptyIterable())).isNull();
}
@Test
public void composeIterableWithOneElement() {
assertThat(ComposableSchemaObjectDefiner.compose(Collections.singleton(this.mockHandlerTwo)))
.isSameAs(this.mockHandlerTwo);
}
@Test
public void composeIterableWithTwoElements() {
SchemaObjectDefiner handler =
ComposableSchemaObjectDefiner.compose(asSet(this.mockHandlerOne, this.mockHandlerTwo));
assertThat(handler).isInstanceOf(ComposableSchemaObjectDefiner.class);
assertThat((ComposableSchemaObjectDefiner) handler)
.containsAll(asSet(this.mockHandlerOne, this.mockHandlerTwo));
}
@Test
public void getSchemaObjectTypesIsComposed() {
when(this.mockHandlerOne.getSchemaObjectTypes())
.thenReturn(asSet(SchemaObjectType.INDEX, SchemaObjectType.LUCENE_INDEX));
when(this.mockHandlerTwo.getSchemaObjectTypes())
.thenReturn(Collections.singleton(SchemaObjectType.DISK_STORE));
SchemaObjectDefiner handler =
ComposableSchemaObjectDefiner.compose(this.mockHandlerOne, this.mockHandlerTwo);
assertThat(handler).isNotNull();
assertThat(handler.getSchemaObjectTypes()).containsAll(
Arrays.asList(SchemaObjectType.INDEX, SchemaObjectType.LUCENE_INDEX, SchemaObjectType.DISK_STORE));
}
@Test
public void defineReturnsRegionDefinition() {
Region<?, ?> mockRegion = mock(Region.class);
when(mockRegion.getName()).thenReturn("MockRegion");
Optional<RegionDefinition> regionDefinition = Optional.of(RegionDefinition.from(mockRegion));
when(this.mockHandlerTwo.canDefine(any(Region.class))).thenReturn(true);
when(this.mockHandlerTwo.define(any(Region.class))).thenAnswer(invocation -> regionDefinition);
SchemaObjectDefiner handler =
ComposableSchemaObjectDefiner.compose(this.mockHandlerOne, this.mockHandlerTwo);
assertThat(handler).isNotNull();
assertThat(handler.define(mockRegion)).isEqualTo(regionDefinition);
verify(this.mockHandlerOne, atMost(1)).canDefine(eq(mockRegion));
verify(this.mockHandlerOne, never()).define(any());
verify(this.mockHandlerTwo, times(1)).canDefine(eq(mockRegion));
verify(this.mockHandlerTwo, times(1)).define(eq(mockRegion));
}
@Test
public void defineReturnsEmptyOptional() {
Object object = new Object();
when(this.mockHandlerOne.canDefine(any(Object.class))).thenReturn(false);
when(this.mockHandlerTwo.canDefine(any(Object.class))).thenReturn(false);
SchemaObjectDefiner handler =
ComposableSchemaObjectDefiner.compose(this.mockHandlerOne, this.mockHandlerTwo);
assertThat(handler).isNotNull();
assertThat(handler.define(object).isPresent()).isFalse();
verify(this.mockHandlerOne, times(1)).canDefine(eq(object));
verify(this.mockHandlerOne, never()).define(any());
verify(this.mockHandlerTwo, times(1)).canDefine(eq(object));
verify(this.mockHandlerTwo, never()).define(any());
}
}

View File

@@ -0,0 +1,148 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.support;
import static java.util.Arrays.stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.query.Index;
import org.apache.geode.cache.query.QueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationContext;
/**
* Unit tests for {@link IndexCollector}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class IndexCollectorUnitTests {
@Mock
private ApplicationContext mockApplicationContext;
@Mock
private GemFireCache mockCache;
private IndexCollector indexCollector = new IndexCollector();
@Mock
private QueryService mockQueryService;
@Before
public void setup() {
when(this.mockCache.getQueryService()).thenReturn(this.mockQueryService);
}
private Index mockIndex(String name) {
Index mockIndex = mock(Index.class, name);
when(mockIndex.getName()).thenReturn(name);
return mockIndex;
}
private Map<String, Index> asMap(Index... indexes) {
return stream(indexes).collect(Collectors.toMap(Index::getName, Function.identity()));
}
@Test
public void collectIndexesFromApplicationContext() {
Index mockIndexOne = mockIndex("MockIndexOne");
Index mockIndexTwo = mockIndex("MockIndexTwo");
Map<String, Index> indexBeans = asMap(mockIndexOne, mockIndexTwo);
when(this.mockApplicationContext.getBeansOfType(eq(Index.class))).thenReturn(indexBeans);
Set<Index> indexes = this.indexCollector.collectFrom(this.mockApplicationContext);
assertThat(indexes).isNotNull();
assertThat(indexes).hasSize(2);
assertThat(indexes).containsAll(asSet(mockIndexOne, mockIndexTwo));
verify(this.mockApplicationContext, times(1)).getBeansOfType(eq(Index.class));
}
@Test
public void collectIndexesFromApplicationContextWhenNoBeansOfTypeIndexExist() {
when(this.mockApplicationContext.getBeansOfType(eq(Index.class))).thenReturn(Collections.emptyMap());
Set<Index> indexes = this.indexCollector.collectFrom(this.mockApplicationContext);
assertThat(indexes).isNotNull();
assertThat(indexes).isEmpty();
verify(this.mockApplicationContext, times(1)).getBeansOfType(eq(Index.class));
}
@Test
public void collectIndexesFromGemFireCache() {
Index mockIndexOne = mockIndex("MockIndexOne");
Index mockIndexTwo = mockIndex("MockIndexTwo");
when(this.mockQueryService.getIndexes()).thenReturn(asSet(mockIndexOne, mockIndexTwo));
Set<Index> indexes = this.indexCollector.collectFrom(this.mockCache);
assertThat(indexes).isNotNull();
assertThat(indexes).hasSize(2);
assertThat(indexes).containsAll(asSet(mockIndexOne, mockIndexTwo));
verify(this.mockCache, times(1)).getQueryService();
verify(this.mockQueryService, times(1)).getIndexes();
}
@Test
public void collectIndexesFromGemFireCacheWhenNoIndexesExist() {
when(this.mockQueryService.getIndexes()).thenReturn(Collections.emptySet());
Set<Index> indexes = this.indexCollector.collectFrom(this.mockCache);
assertThat(indexes).isNotNull();
assertThat(indexes).isEmpty();
verify(this.mockCache, times(1)).getQueryService();
verify(this.mockQueryService, times(1)).getIndexes();
}
}

View File

@@ -0,0 +1,127 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.Index;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.IndexType;
import org.springframework.data.gemfire.config.schema.SchemaObjectType;
import org.springframework.data.gemfire.config.schema.definitions.IndexDefinition;
/**
* Unit tests for {@link IndexDefiner}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.apache.geode.cache.query.Index
* @see org.springframework.data.gemfire.IndexType
* @see org.springframework.data.gemfire.config.schema.definitions.IndexDefinition
* @see IndexDefiner
* @since 1.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class IndexDefinerUnitTests {
@Mock
private Index mockIndex;
@Mock
private Region<?, ?> mockRegion;
private IndexDefiner indexInstanceHandler = new IndexDefiner();
@Before
@SuppressWarnings("unchecked")
public void setup() {
when(this.mockIndex.getName()).thenReturn("MockIndex");
when(this.mockIndex.getIndexedExpression()).thenReturn("testExpression");
when(this.mockIndex.getFromClause()).thenReturn("/TestFromClause");
when(this.mockIndex.getType()).thenReturn(IndexType.HASH.getGemfireIndexType());
}
@Test
public void canHandleIndexInstanceIsTrue() {
assertThat(this.indexInstanceHandler.canDefine(this.mockIndex)).isTrue();
}
@Test
public void canHandleNullInstanceIsFalse() {
assertThat(this.indexInstanceHandler.canDefine((Object) null)).isFalse();
}
@Test
public void canHandleRegionInstanceIsFalse() {
assertThat(this.indexInstanceHandler.canDefine(this.mockRegion)).isFalse();
}
@Test
public void canHandleIndexTypeIsTrue() {
assertThat(this.indexInstanceHandler.canDefine(Index.class)).isTrue();
}
@Test
public void canHandleNullTypeIsFalse() {
assertThat(this.indexInstanceHandler.canDefine((Class<?>) null)).isFalse();
}
@Test
public void canHandleRegionTypeIsFalse() {
assertThat(this.indexInstanceHandler.canDefine(Region.class)).isFalse();
}
@Test
public void canHandleIndexSchemaObjectTypeIsTrue() {
assertThat(this.indexInstanceHandler.canDefine(SchemaObjectType.INDEX)).isTrue();
}
@Test
public void canHandleNullSchemaObjectTypeIsFalse() {
assertThat(this.indexInstanceHandler.canDefine((SchemaObjectType) null)).isFalse();
}
@Test
public void canHandleRegionSchemaObjectTypeIsFalse() {
assertThat(this.indexInstanceHandler.canDefine(SchemaObjectType.REGION)).isFalse();
}
@Test
public void defineForIndexObject() {
IndexDefinition indexDefinition = this.indexInstanceHandler.define(this.mockIndex).orElse(null);
assertThat(indexDefinition).isNotNull();
assertThat(indexDefinition.getExpression()).isEqualTo("testExpression");
assertThat(indexDefinition.getFromClause()).isEqualTo("/TestFromClause");
assertThat(indexDefinition.getIndexType()).isEqualTo(IndexType.HASH);
assertThat(indexDefinition.getType()).isEqualTo(SchemaObjectType.INDEX);
}
@Test
public void defineForRegionObject() {
assertThat(this.indexInstanceHandler.define(this.mockRegion).isPresent()).isFalse();
}
}

View File

@@ -0,0 +1,140 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.support;
import static java.util.Arrays.stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.Region;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationContext;
/**
* Unit tests for {@link RegionCollector}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.config.schema.support.RegionCollector
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class RegionCollectorUnitTests {
@Mock
private ApplicationContext mockApplicationContext;
@Mock
private GemFireCache mockCache;
private RegionCollector regionCollector = new RegionCollector();
@SuppressWarnings("unchecked")
private <K, V> Region<K, V> mockRegion(String name) {
Region<K, V> mockRegion = mock(Region.class, name);
when(mockRegion.getName()).thenReturn(name);
return mockRegion;
}
private Map<String, Region> asMap(Region<?, ?>... regions) {
return stream(regions).collect(Collectors.toMap(Region::getName, Function.identity()));
}
@Test
public void collectRegionsFromApplicationContext() {
Region mockRegionOne = mockRegion("MockRegionOne");
Region mockRegionTwo = mockRegion("MockRegionTwo");
Map<String, Region> regionBeans = asMap(mockRegionOne, mockRegionTwo);
when(this.mockApplicationContext.getBeansOfType(eq(Region.class))).thenReturn(regionBeans);
Set<Region> actualRegions = this.regionCollector.collectFrom(this.mockApplicationContext);
assertThat(actualRegions).isNotNull();
assertThat(actualRegions).hasSize(2);
assertThat(actualRegions).containsAll(asSet(mockRegionOne, mockRegionTwo));
verify(this.mockApplicationContext, times(1)).getBeansOfType(eq(Region.class));
}
@Test
public void collectRegionsFromApplicationContextWhenNoBeansOfTypeRegionExist() {
when(this.mockApplicationContext.getBeansOfType(eq(Region.class))).thenReturn(Collections.emptyMap());
Set<Region> actualRegions = this.regionCollector.collectFrom(this.mockApplicationContext);
assertThat(actualRegions).isNotNull();
assertThat(actualRegions).isEmpty();
verify(this.mockApplicationContext, times(1)).getBeansOfType(eq(Region.class));
}
@Test
@SuppressWarnings("unchecked")
public void collectRegionsFromGemFireCache() {
Region mockRegionOne = mockRegion("MockRegionOne");
Region mockRegionTwo = mockRegion("MockRegionTwo");
when(this.mockCache.rootRegions()).thenReturn(asSet(mockRegionOne, mockRegionTwo));
Set<Region> actualRegions = this.regionCollector.collectFrom(this.mockCache);
assertThat(actualRegions).isNotNull();
assertThat(actualRegions).hasSize(2);
assertThat(actualRegions).containsAll(asSet(mockRegionOne, mockRegionTwo));
verify(this.mockCache, times(1)).rootRegions();
}
@Test
@SuppressWarnings("unchecked")
public void collectRegionsFromGemFireCacheWhenNoRootRegionsExist() {
when(this.mockCache.rootRegions()).thenReturn(Collections.emptySet());
Set<Region> actualRegions = this.regionCollector.collectFrom(this.mockCache);
assertThat(actualRegions).isNotNull();
assertThat(actualRegions).isEmpty();
verify(this.mockCache, times(1)).rootRegions();
}
}

View File

@@ -0,0 +1,140 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed 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.springframework.data.gemfire.config.schema.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.query.Index;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.gemfire.config.schema.SchemaObjectType;
import org.springframework.data.gemfire.config.schema.definitions.RegionDefinition;
/**
* Unit tests for {@link RegionDefiner}.
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.apache.geode.cache.Region
* @see org.springframework.data.gemfire.config.schema.definitions.RegionDefinition
* @since 2.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class RegionDefinerUnitTests {
@Mock
private Index mockIndex;
@Mock
private Region<Object, Object> mockRegion;
private RegionDefiner regionInstanceHandler = new RegionDefiner();
@Before
public void setup() {
when(this.mockRegion.getName()).thenReturn("MockRegion");
}
@Test
public void canHandleIndexInstanceIsFalse() {
assertThat(this.regionInstanceHandler.canDefine(this.mockIndex)).isFalse();
}
@Test
public void canHandleNullInstanceIsFalse() {
assertThat(this.regionInstanceHandler.canDefine((Object) null)).isFalse();
}
@Test
public void canHandleRegionInstanceIsTrue() {
assertThat(this.regionInstanceHandler.canDefine(this.mockRegion)).isTrue();
}
@Test
public void canHandleIndexTypeIsFalse() {
assertThat(this.regionInstanceHandler.canDefine(Index.class)).isFalse();
}
@Test
public void canHandleNullTypeIsFalse() {
assertThat(this.regionInstanceHandler.canDefine((Class<?>) null)).isFalse();
}
@Test
public void canHandleRegionTypeIsTrue() {
assertThat(this.regionInstanceHandler.canDefine(Region.class)).isTrue();
}
@Test
public void canHandleIndexSchemaObjectTypeIsFalse() {
assertThat(this.regionInstanceHandler.canDefine(SchemaObjectType.INDEX)).isFalse();
}
@Test
public void canHandleNullSchemaObjectTypeIsFalse() {
assertThat(this.regionInstanceHandler.canDefine((SchemaObjectType) null)).isFalse();
}
@Test
public void canHandleRegionSchemaObjectTypeIsTrue() {
assertThat(this.regionInstanceHandler.canDefine(SchemaObjectType.REGION)).isTrue();
}
@Test
@SuppressWarnings("unchecked")
public void defineClientRegion() {
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(this.mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
when(mockRegionAttributes.getPoolName()).thenReturn("TestPool");
RegionDefinition regionDefinition = this.regionInstanceHandler.define(this.mockRegion).orElse(null);
assertThat(regionDefinition).isNotNull();
assertThat(regionDefinition.getName()).isEqualTo(this.mockRegion.getName());
assertThat(regionDefinition.getRegionShortcut()).isEqualTo(RegionShortcut.PARTITION);
assertThat(regionDefinition.getType()).isEqualTo(SchemaObjectType.REGION);
}
@Test
@SuppressWarnings("unchecked")
public void definePeerRegion() {
RegionAttributes<Object, Object> mockRegionAttributes = mock(RegionAttributes.class);
when(this.mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
when(mockRegionAttributes.getPoolName()).thenReturn(" ");
assertThat(this.regionInstanceHandler.define(this.mockRegion).isPresent()).isFalse();
}
@Test
public void defineWithNull() {
assertThat(this.regionInstanceHandler.define(null).isPresent()).isFalse();
}
}

View File

@@ -16,8 +16,13 @@
package org.springframework.data.gemfire.test.support;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -35,19 +40,57 @@ public abstract class IOUtils {
/* (non-Javadoc) */
public static boolean close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
return true;
}
catch (IOException ignore) {
catch (IOException cause) {
if (log.isLoggable(Level.FINE)) {
log.fine(String.format("Failed to close the Closeable object (%1$s) due to an I/O error:%n%2$s",
closeable, ThrowableUtils.toString(ignore)));
closeable, ThrowableUtils.toString(cause)));
}
}
}
return false;
}
/* (non-Javadoc) */
@SuppressWarnings("unchecked")
public static <T> T deserializeObject(byte[] objectBytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(objectBytes);
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(byteArrayInputStream);
return (T) objectInputStream.readObject();
}
finally {
IOUtils.close(objectInputStream);
}
}
/* (non-Javadoc) */
public static byte[] serializeObject(Serializable obj) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
return byteArrayOutputStream.toByteArray();
}
finally {
IOUtils.close(objectOutputStream);
}
}
}