repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/ODataJPAQueryContextTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/ODataJPAQueryContextTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
class ODataJPAQueryContextTest {
private JPAVisitor jpaVisitor;
private JPAEntityType et;
private From<?, ?> from;
private CriteriaBuilder cb;
private ODataJPAQueryContext cut;
@BeforeEach
void setUp() {
jpaVisitor = mock(JPAVisitor.class);
from = mock(From.class);
et = mock(JPAEntityType.class);
cb = mock(CriteriaBuilder.class);
when(jpaVisitor.getEntityType()).thenReturn(et);
when(jpaVisitor.getCriteriaBuilder()).thenReturn(cb);
doReturn(from).when(jpaVisitor).getRoot();
cut = new ODataJPAQueryContext(jpaVisitor);
}
@Test
void testGetEntityType() {
assertEquals(et, cut.getEntityType());
}
@Test
void testGetFrom() {
assertEquals(from, cut.getFrom());
}
@Test
void testGetCriteriaBuilder() {
assertEquals(cb, cut.getCriteriaBuilder());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPANullExpressionTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPANullExpressionTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
class JPANullExpressionTest {
private JPANullExpression cut;
private Literal literal;
private BinaryOperatorKind operator;
private Member member;
@BeforeEach
void setup() {
literal = mock(Literal.class);
member = mock(Member.class);
}
@Test
void checkGetMember() throws ODataJPAFilterException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
operator = BinaryOperatorKind.EQ;
cut = new JPANullExpression(member, literal, operator);
assertEquals(uriInfo, cut.getMember());
}
@Test
void checkAcceptReturnsNull() throws ExpressionVisitException, ODataApplicationException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
operator = BinaryOperatorKind.EQ;
cut = new JPANullExpression(member, literal, operator);
assertNull(cut.accept(null));
}
@Test
void checkIsInvertedDefaultFalse() throws ODataJPAFilterException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
when(literal.getText()).thenReturn("null");
operator = BinaryOperatorKind.NE;
cut = new JPANullExpression(member, literal, operator);
assertFalse(cut.isInversionRequired());
}
@Test
void checkIsInvertedTrueNeZero() throws ODataJPAFilterException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
when(literal.getText()).thenReturn("null");
operator = BinaryOperatorKind.EQ;
cut = new JPANullExpression(member, literal, operator);
assertTrue(cut.isInversionRequired());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterRestrictionsWatchDogTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterRestrictionsWatchDogTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlCollection;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlDynamicExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyPath;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyValue;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlRecord;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
class JPAFilterRestrictionsWatchDogTest {
private JPAFilterRestrictionsWatchDog cut;
private JPAAnnotatable annotatable;
private CsdlAnnotation annotation;
private CsdlConstantExpression filterable;
private CsdlConstantExpression filterRequired;
private List<CsdlExpression> requiredProperties;
@BeforeEach
void setup() throws ODataJPAQueryException {
annotatable = mock(JPAAnnotatable.class);
annotation = mock(CsdlAnnotation.class);
cut = new JPAFilterRestrictionsWatchDog(annotatable, false);
}
private static Stream<Arguments> provideFilteringIsSupported() {
return Stream.of(
Arguments.of(false, false, false),
Arguments.of(true, false, true),
Arguments.of(true, true, false));
}
@ParameterizedTest
@MethodSource("provideFilteringIsSupported")
void testHandleIfFilterIsSupportedAndExpressionGiven(final boolean isAnnotated, final boolean annotatedValue,
final boolean throwsException) throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
@SuppressWarnings("unchecked")
final Expression<Boolean> filter = mock(Expression.class);
when(filterable.getValue()).thenReturn(Boolean.toString(annotatedValue));
// when(filterRequired.getValue()).thenReturn(Boolean.toString(false));
cut = new JPAFilterRestrictionsWatchDog(annotatable, false);
assertShallThrow(throwsException, filter);
}
private static Stream<Arguments> provideFilteringIsRequired() {
return Stream.of(
Arguments.of(false, false, false),
Arguments.of(true, false, false),
Arguments.of(true, true, true));
}
@ParameterizedTest
@MethodSource("provideFilteringIsRequired")
void testHandleIfFilterIsRequiredAndExpressionNotGiven(final boolean isAnnotated, final boolean annotatedValue,
final boolean throwsException) throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
when(filterRequired.getValue()).thenReturn(Boolean.toString(annotatedValue));
cut = new JPAFilterRestrictionsWatchDog(annotatable, false);
assertShallThrow(throwsException, null);
}
@Test
void testHandleBuildRequiredProperties() throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(true);
requiredProperties.add(createAnnotationPath("AlternativeCode"));
requiredProperties.add(createAnnotationPath("AlternativeId"));
cut = new JPAFilterRestrictionsWatchDog(annotatable, false);
assertEquals(2, cut.getRequiredPropertyPath().size());
}
@Test
void testHandleVisitedProperty() throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(true);
requiredProperties.add(createAnnotationPath("AlternativeCode"));
requiredProperties.add(createAnnotationPath("AlternativeId"));
cut = new JPAFilterRestrictionsWatchDog(annotatable, false);
final JPAPath firstPath = mock(JPAPath.class);
when(firstPath.getAlias()).thenReturn("AlternativeCode");
cut.watch(firstPath);
assertEquals(1, cut.getRequiredPropertyPath().size());
final JPAPath secondPath = mock(JPAPath.class);
when(secondPath.getAlias()).thenReturn("Code");
cut.watch(secondPath);
assertEquals(1, cut.getRequiredPropertyPath().size());
final JPAPath thirdPath = mock(JPAPath.class);
when(thirdPath.getAlias()).thenReturn("AlternativeId");
cut.watch(thirdPath);
assertTrue(cut.getRequiredPropertyPath().isEmpty());
}
@Test
void testHandleNotAllPropertiesUsed() throws ODataJPAModelException, ODataJPAQueryException {
@SuppressWarnings("unchecked")
final Expression<Boolean> filter = mock(Expression.class);
setAnnotation(true);
requiredProperties.add(createAnnotationPath("AlternativeId"));
when(filterable.getValue()).thenReturn(Boolean.toString(true));
when(filterRequired.getValue()).thenReturn(Boolean.toString(true));
cut = new JPAFilterRestrictionsWatchDog(annotatable, false);
assertThrows(ODataJPAFilterException.class, () -> cut.watch(filter));
}
@Test
void testHandleNotAllPropertiesUsedButNotRequired() throws ODataJPAModelException, ODataJPAQueryException {
@SuppressWarnings("unchecked")
final Expression<Boolean> filter = mock(Expression.class);
setAnnotation(true);
requiredProperties.add(createAnnotationPath("AlternativeId"));
when(filterable.getValue()).thenReturn(Boolean.toString(true));
when(filterRequired.getValue()).thenReturn(Boolean.toString(false));
cut = new JPAFilterRestrictionsWatchDog(annotatable, false);
assertDoesNotThrow(() -> cut.watch(filter));
}
// Filter not required but required properties
@Test
void testHandleFilterIsRequiredAndKeyRequested() throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(true);
when(filterRequired.getValue()).thenReturn(Boolean.toString(true));
cut = new JPAFilterRestrictionsWatchDog(annotatable, true);
assertDoesNotThrow(() -> cut.watch((Expression<Boolean>) null));
}
private void assertShallThrow(final boolean throwsException, final Expression<Boolean> filter) {
if (throwsException)
assertThrows(ODataJPAFilterException.class, () -> cut.watch(filter));
else
assertDoesNotThrow(() -> cut.watch(filter));
}
private void setAnnotation(final boolean isAnnotated) throws ODataJPAModelException {
initAnnotation();
if (isAnnotated)
when(annotatable.getAnnotation(JPAFilterRestrictionsWatchDog.VOCABULARY_ALIAS,
JPAFilterRestrictionsWatchDog.TERM))
.thenReturn(annotation);
else
when(annotatable.getAnnotation(JPAFilterRestrictionsWatchDog.VOCABULARY_ALIAS,
JPAFilterRestrictionsWatchDog.TERM))
.thenReturn(null);
}
private CsdlPropertyPath createAnnotationPath(final String pathString) {
final CsdlPropertyPath path = mock(CsdlPropertyPath.class);
when(path.asPropertyPath()).thenReturn(path);
when(path.asDynamic()).thenReturn(path);
when(path.getValue()).thenReturn(pathString);
return path;
}
private void initAnnotation() {
final CsdlDynamicExpression expression = mock(CsdlDynamicExpression.class);
final CsdlRecord record = mock(CsdlRecord.class);
filterable = mock(CsdlConstantExpression.class);
filterRequired = mock(CsdlConstantExpression.class);
requiredProperties = new ArrayList<>();
final CsdlPropertyValue filterableValue = createSingleExpression(filterable,
JPAFilterRestrictionsWatchDog.FILTERABLE);
final CsdlPropertyValue filterRequiredValue = createSingleExpression(filterRequired,
JPAFilterRestrictionsWatchDog.REQUIRES_FILTER);
final CsdlPropertyValue requiredPropertiesValue = createCollectionExpression(requiredProperties,
JPAFilterRestrictionsWatchDog.REQUIRED_PROPERTIES);
final List<CsdlPropertyValue> propertyValues = Arrays.asList(filterableValue, filterRequiredValue,
requiredPropertiesValue);
when(annotation.getExpression()).thenReturn(expression);
when(expression.asDynamic()).thenReturn(expression);
when(expression.asRecord()).thenReturn(record);
when(record.getPropertyValues()).thenReturn(propertyValues);
}
private CsdlPropertyValue createSingleExpression(final CsdlConstantExpression expression,
final String property) {
final CsdlPropertyValue value = mock(CsdlPropertyValue.class);
when(value.getProperty()).thenReturn(property);
when(value.getValue()).thenReturn(expression);
when(expression.asConstant()).thenReturn(expression);
return value;
}
private CsdlPropertyValue createCollectionExpression(final List<CsdlExpression> collection,
final String property) {
final CsdlPropertyValue value = mock(CsdlPropertyValue.class);
final CsdlCollection csdlCollection = mock(CsdlCollection.class);
when(value.getProperty()).thenReturn(property);
when(value.getValue()).thenReturn(csdlCollection);
when(csdlCollection.getItems()).thenReturn(collection);
when(csdlCollection.asDynamic()).thenReturn(csdlCollection);
when(csdlCollection.asCollection()).thenReturn(csdlCollection);
return value;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestRetrieveSingleEntity extends TestBase {
@Test
void testRetrieveWithOneKey() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertEquals("3", organization.get("ID").asText());
}
@Test
void testRetrieveWithTwoKeys() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertEquals("1", organization.get("BusinessPartnerID").asText());
assertEquals("A", organization.get("RoleCategory").asText());
}
@Test
void testRetrieveWithEmbeddedKey() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='en')");
helper.assertStatus(200);
final ObjectNode description = helper.getValue();
assertEquals("en", description.get("Language").asText());
assertEquals("NUTS1", description.get("CodeID").asText());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPALiteralOperatorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPALiteralOperatorTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.stream.Stream;
import org.apache.olingo.commons.core.edm.primitivetype.SingletonPrimitiveType;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.reflections8.Reflections;
import org.reflections8.scanners.SubTypesScanner;
import org.reflections8.util.ConfigurationBuilder;
class JPALiteralOperatorTest {
private static OData odata = OData.newInstance();
@TestFactory
Stream<DynamicTest> testNonGeometryPrimitiveTypeAreConverted() {
final ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setScanners(new SubTypesScanner(false));
configBuilder.forPackages(SingletonPrimitiveType.class.getPackage().getName());
final Reflections reflection = new Reflections(configBuilder);
final Set<Class<? extends SingletonPrimitiveType>> edmPrimitiveTypes = reflection.getSubTypesOf(
SingletonPrimitiveType.class);
return edmPrimitiveTypes
.stream()
.filter(type -> type.getSuperclass() == SingletonPrimitiveType.class)
.map(JPALiteralOperatorTest::createEdmPrimitiveType)
.filter(i -> i != null)
.map(JPALiteralOperatorTest::createLiteralOperator)
.map(operator -> dynamicTest(operator.getLiteral().getType().getName(), () -> assertTypeConversion(operator)));
}
private void assertTypeConversion(final JPALiteralOperator operator) throws ODataApplicationException {
final Object act = operator.get();
assertNotNull(act);
assertFalse(act.toString().contains("'"));
}
private static SingletonPrimitiveType createEdmPrimitiveType(
final Class<? extends SingletonPrimitiveType> typeClass) {
try {
final Method method = typeClass.getMethod("getInstance");
return (SingletonPrimitiveType) method.invoke(null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
| SecurityException e) {
return null;
}
}
private static JPALiteralOperator createLiteralOperator(final SingletonPrimitiveType typeInstance) {
final Literal literal = mock(Literal.class);
when(literal.getType()).thenReturn(typeInstance);
when(literal.getText()).thenReturn(determineLiteral(typeInstance));
return new JPALiteralOperator(odata, literal);
}
private static String determineLiteral(final SingletonPrimitiveType typeInstance) {
switch (typeInstance.getName()) {
case "Guid":
return "819a3e3b-837e-4ecb-a600-654ef7b5aace";
case "Date":
return "2021-10-01";
case "Boolean":
return "true";
case "TimeOfDay":
return "10:00:12.10";
case "DateTimeOffset":
return "2021-10-01T10:00:12Z";
case "Duration":
return "P2DT12H30M5S";
default:
return "123";
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.apache.olingo.commons.api.http.HttpStatusCode.FORBIDDEN;
import static org.apache.olingo.commons.api.http.HttpStatusCode.OK;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import java.io.IOException;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.metadata.odata.v4.provider.JavaBasedCapabilitiesAnnotationsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.util.Assertions;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQueryWhereClause extends TestBase {
static Stream<Arguments> getFilterQuery() {
return Stream.of(
// Simple filter
arguments("OneNotEqual", "Organizations?$filter=ID ne '3'", 9),
// '10' is smaller than '5' when comparing strings!
arguments("OneGreaterEquals", "Organizations?$filter=ID ge '5'", 5),
arguments("OneLowerThanTwo", "AdministrativeDivisions?$filter=DivisionCode lt CountryCode", 244),
arguments("OneGreaterThan", "Organizations?$filter=ID gt '5'", 4),
arguments("OneLowerThan", "Organizations?$filter=ID lt '5'", 5),
arguments("OneLowerEquals", "Organizations?$filter=ID le '5'", 6),
arguments("OneGreaterEqualsNumber", "AdministrativeDivisions?$filter=Area ge 119330610", 4),
arguments("OneAndEquals", "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and CodeID eq 'NUTS2'",
11),
arguments("OneOrEquals", "Organizations?$filter=ID eq '5' or ID eq '10'", 2),
arguments("OneNotLower", "AdministrativeDivisions?$filter=not (Area lt 50000000)", 24),
arguments("AddGreater", "AdministrativeDivisions?$filter=Area add 7000000 ge 50000000", 31),
arguments("SubGreater", "AdministrativeDivisions?$filter=Area sub 7000000 ge 60000000", 15),
arguments("DivGreater", "AdministrativeDivisions?$filter=Area gt 0 and Area div Population ge 6000", 9),
arguments("MulGreater", "AdministrativeDivisions?$filter=Area mul Population gt 0", 64),
arguments("Mod", "AdministrativeDivisions?$filter=Area gt 0 and Area mod 3578335 eq 0", 1),
arguments("Length", "AdministrativeDivisionDescriptions?$filter=length(Name) eq 10", 11),
arguments("Now", "Persons?$filter=AdministrativeInformation/Created/At lt now()", 3),
arguments("Contains", "AdministrativeDivisions?$filter=contains(CodeID,'166')", 110),
arguments("Endswith", "AdministrativeDivisions?$filter=endswith(CodeID,'166-1')", 4),
arguments("Startswith", "AdministrativeDivisions?$filter=startswith(DivisionCode,'DE-')", 16),
arguments("Not Startswith", "AdministrativeDivisions?$filter=not startswith(DivisionCode,'BE')", 176),
arguments("IndexOf", "AdministrativeDivisions?$filter=indexof(DivisionCode,'3') eq 4", 7),
arguments("SubstringStartIndex",
"AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,6) eq 'Dakota'", 2),
arguments("SubstringStartEndIndex",
"AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,0,5) eq 'North'", 2),
arguments("SubstringLengthCalculated",
"AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,0,1 add 4) eq 'North'", 2),
arguments("ToLower",
"AdministrativeDivisionDescriptions?$filter=Language eq 'de' and tolower(Name) eq 'brandenburg'", 1),
arguments("ToUpper",
"AdministrativeDivisionDescriptions?$filter=Language eq 'de' and toupper(Name) eq 'HESSEN'", 1),
arguments("ToUpperInverse", "AdministrativeDivisions?$filter=toupper('nuts1') eq CodeID", 19),
arguments("Trim", "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and trim(Name) eq 'Sachsen'", 1),
arguments("Concat", "Persons?$filter=concat(concat(LastName,','),FirstName) eq 'Mustermann,Max'", 1),
arguments("OneHas", "Persons?$filter=AccessRights has com.sap.olingo.jpa.AccessRights'READ'", 1),
arguments("OnNull", "AdministrativeDivisions?$filter=CodePublisher eq 'ISO' and ParentCodeID eq null", 4),
arguments("OneEqualsTwoProperties", "AdministrativeDivisions?$filter=DivisionCode eq CountryCode", 4),
arguments("SubstringStartEndIndexToLower",
"AdministrativeDivisionDescriptions?$filter=Language eq 'de' and tolower(substring(Name,0,5)) eq 'north'",
2),
// Filter on property with converter
arguments("Property with converter, from boolean to string", "Teams?$filter=Active eq false", 2),
// IN expression
arguments("Simple IN", "AdministrativeDivisions?$filter=ParentDivisionCode in ('BE1', 'BE2')", 6),
arguments("Simple NOT IN", "AdministrativeDivisions?$filter=not (ParentDivisionCode in ('BE1', 'BE2'))", 219),
arguments("IN via navigation", "AdministrativeDivisions?$filter=Parent/ParentDivisionCode in ('BE2')", 22),
// Filter to many associations
arguments("NavigationPropertyToManyValueAnyNoRestriction", "Organizations?$select=ID&$filter=Roles/any()", 4),
arguments("NavigationPropertyToManyValueAnyMultiParameter",
"Organizations?$select=ID&$filter=Roles/any(d:d/RoleCategory eq 'A' and d/BusinessPartnerID eq '1')", 1),
arguments("NavigationPropertyToManyValueNotAny",
"Organizations?$filter=not (Roles/any(d:d/RoleCategory eq 'A'))", 7),
arguments("NavigationPropertyToManyValueAny",
"Organizations?$select=ID&$filter=Roles/any(d:d/RoleCategory eq 'A')", 3),
arguments("NavigationPropertyToManyValueAll",
"Organizations?$select=ID&$filter=Roles/all(d:d/RoleCategory eq 'A')", 1),
arguments("NavigationPropertyToManyNested2Level",
"AdministrativeDivisions?$filter=Children/any(c:c/Children/any(cc:cc/ParentDivisionCode eq 'BE25'))", 1),
arguments("NavigationPropertyToManyNested3Level",
"AdministrativeDivisions?$filter=Children/any(c:c/Children/any(cc:cc/Children/any(ccc:ccc/ParentDivisionCode eq 'BE251')))",
1),
arguments("NavigationPropertyToManyNestedWithJoinTable",
"Organizations?$select=ID&$filter=SupportEngineers/any(s:s/AdministrativeInformation/Created/User/Roles/any(a:a/RoleCategory eq 'Y'))",
2),
arguments("NavigationPropertyFromInheritance",
"InheritanceSavingAccounts?$select=AccountId&$filter=Transactions/any()", 2),
arguments("NavigationPropertyToInheritance",
"Persons?$select=ID&$filter=Accounts/any(s:s/com.sap.olingo.jpa.InheritanceLockedSavingAccount/InterestRate gt 3.0)",
1),
arguments("NavigationPropertyDescriptionViaComplexTypeWOSubselectSelectAll",
"Organizations?$filter=Address/RegionName eq 'Kalifornien'", 3),
arguments("NavigationPropertyDescriptionViaComplexTypeWOSubselectSelectId",
"Organizations?$filter=Address/RegionName eq 'Kalifornien'&$select=ID", 3),
arguments("NavigationPropertyDescriptionToOneValueViaComplexTypeWSubselect1",
"Organizations?$filter=AdministrativeInformation/Created/User/LocationName eq 'Schweiz'", 1),
arguments("NavigationPropertyDescriptionToOneValueViaComplexTypeWSubselect2",
"Organizations?$filter=AdministrativeInformation/Created/User/LocationName eq 'Schweiz'&$select=ID", 1),
// Filter collection property
arguments("CountCollectionPropertyOne",
"Persons?$select=ID&$filter=InhouseAddress/any(d:d/Building eq '7')", 1),
arguments("CollectionPropertyViaCast",
"Organizations?$select=ID&$filter=SupportEngineers/any(s:s/InhouseAddress/any(a:a/Building eq '2'))", 2),
// https://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398301
// Example 43: return all Categories with less than 10 products
// Filter to many associations count
arguments("NoChildren", "AdministrativeDivisions?$filter=Children/$count eq 0", 220),
arguments("CountNavigationPropertyTwo", "Organizations?$select=ID&$filter=Roles/$count eq 2", 1),
arguments("CountNavigationPropertyZero", "Organizations?$select=ID&$filter=Roles/$count eq 0", 6),
arguments("CountNavigationPropertyMultipleHops",
"Organizations?$select=ID&$filter=AdministrativeInformation/Created/User/Roles/$count ge 2", 8),
arguments("CountNavigationPropertyMultipleHopsNavigations not zero",
"AdministrativeDivisions?$filter=Parent/Children/$count eq 2", 2),
arguments("CountNavigationPropertyMultipleHopsNavigations zero",
"AdministrativeDivisions?$filter=Parent/Children/$count eq 0", 0),
arguments("CountNavigationPropertyJoinTable not zero", "JoinSources?$filter=OneToMany/$count eq 4", 1),
// Filter collection property count
arguments("CountCollectionPropertyOne", "Organizations?$select=ID&$filter=Comment/$count ge 1", 2),
arguments("CountCollectionPropertyTwoJoinOne", "CollectionWithTwoKeys?$filter=Nested/$count eq 1", 1),
arguments("CountCollectionPropertyTwoJoinZero", "CollectionWithTwoKeys?$filter=Nested/$count eq 0", 3),
// To one association null
arguments("NavigationPropertyIsNullOneHop",
"AdministrativeDivisions?$filter=Parent/Parent eq null and CodePublisher eq 'Eurostat'", 11),
arguments("NavigationPropertyMixCountAndNull",
"AdministrativeDivisions?$filter=Parent/Children/$count eq 2 and Parent/Parent/Parent eq null", 2),
arguments("NavigationPropertyIsNullJoinTable", "JoinTargets?$filter=ManyToOne ne null", 4),
// Filter to one association
arguments("NavigationPropertyToOneValue", "AdministrativeDivisions?$filter=Parent/CodeID eq 'NUTS1'", 11),
arguments("NavigationPropertyToOneValueAndEquals",
"AdministrativeDivisions?$filter=Parent/CodeID eq 'NUTS1' and DivisionCode eq 'BE34'", 1),
arguments("NavigationPropertyToOneValueTwoHops",
"AdministrativeDivisions?$filter=Parent/Parent/CodeID eq 'NUTS1' and DivisionCode eq 'BE212'", 1),
arguments("NavigationPropertyToOneValueViaComplexType",
"Organizations?$filter=AdministrativeInformation/Created/User/LastName eq 'Mustermann'", 8));
}
static Stream<Arguments> getFilterQueryDerivedProperty() {
return Stream.of(
// To one association null
arguments("NavigationPropertyIsNull",
"AssociationOneToOneSources?$format=json&$filter=ColumnTarget eq null", 1),
arguments("NavigationPropertyIsNull",
"AssociationOneToOneSources?$format=json&$filter=ColumnTarget ne null", 3));
}
static Stream<Arguments> getEnumQuery() {
return Stream.of(
arguments("OneEnumNotEqual", "Persons?$filter=AccessRights ne com.sap.olingo.jpa.AccessRights'WRITE'", "97"),
arguments("OneEnumEqualMultipleValues",
"Persons?$filter=AccessRights eq com.sap.olingo.jpa.AccessRights'READ,DELETE'", "97")
// @Disabled("Clarify if GT, LE .. not supported by OData or \"only\" by Olingo")
// arguments("OneEnumGreaterThan", "Persons?$filter=AccessRights gt com.sap.olingo.jpa.AccessRights'Read'", "99")
);
}
static Stream<Arguments> getFilterCollectionQuery() {
return Stream.of(
arguments("SimpleCount", "Persons?$filter=InhouseAddress/$count eq 2", 1),
arguments("SimpleCountViaJoinTable",
"JoinSources?$filter=OneToMany/$count gt 1&$select=SourceID", 1),
arguments("DeepSimpleCount",
"CollectionDeeps?$filter=FirstLevel/SecondLevel/Comment/$count eq 2&$select=ID", 1),
arguments("DeepComplexCount",
"CollectionDeeps?$filter=FirstLevel/SecondLevel/Address/$count eq 2&$select=ID", 1),
arguments("DeepSimpleCountZero",
"CollectionDeeps?$filter=FirstLevel/SecondLevel/Comment/$count eq 0&$select=ID", 1),
arguments("Any", "Organizations?$select=ID&$filter=Comment/any(s:contains(s, 'just'))", 1),
arguments("AsPartOfComplexAny",
"CollectionDeeps?$filter=FirstLevel/SecondLevel/Address/any(s:s/TaskID eq 'DEV')", 1));
}
static Stream<Arguments> getFilterNavigationPropertyRequiresGroupsQuery() {
return Stream.of(
arguments("NavigationRequiresGroupsProvided",
"BusinessPartnerWithGroupss?$select=ID&$filter=Roles/any(d:d/Details eq 'A')", OK),
arguments("CollectionRequiresGroupsReturnsForbidden",
"BusinessPartnerWithGroupss?$select=ID&$filter=Comment/any(s:contains(s, 'just'))", FORBIDDEN),
arguments("CollectionRequiresGroupsProvided",
"BusinessPartnerWithGroupss?$select=ID&$filter=Comment/any(s:contains(s, 'just'))", OK),
arguments("CollectionProtectedPropertyRequiresGroupsReturnsForbidden",
"BusinessPartnerWithGroupss('99')/InhouseAddress?$filter=RoomNumber eq 1", FORBIDDEN),
arguments("CollectionProtectedPropertyRequiresGroupsProvided",
"BusinessPartnerWithGroupss('99')/InhouseAddress?$filter=RoomNumber eq 1", OK));
}
@Test
void testFilterOneEquals() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$filter=ID eq '3'");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(1, organizations.size());
assertEquals("3", organizations.get(0).get("ID").asText());
}
@Test
void testFilterOneEqualsDateTime() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$filter=CreationDateTime eq 2016-01-20T09:21:23Z");
helper.assertStatus(200);
// This test shall ensure that the Date Time value is mapped correct.
// Unfortunately the query returns an empty result locally, but 10 rows on Jenkins
final ArrayNode organizations = helper.getValues();
assertNotNull(organizations);
}
@Test
void testFilterOneDescriptionEquals() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$filter=LocationName eq 'Deutschland'");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(1, organizations.size());
assertEquals("10", organizations.get(0).get("ID").asText());
}
@Test
void testFilterOneDescriptionEqualsFieldNotSelected() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$filter=LocationName eq 'Deutschland'&$select=ID");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(1, organizations.size());
assertEquals("10", organizations.get(0).get("ID").asText());
}
@Test
void testFilterOneEnumEquals() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$filter=ABCClass eq com.sap.olingo.jpa.ABCClassification'A'");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(1, organizations.size());
assertEquals("1", organizations.get(0).get("ID").asText());
}
@Test
void testFilterOneEqualsInvert() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter='3' eq ID");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(1, organizations.size());
assertEquals("3", organizations.get(0).get("ID").asText());
}
@ParameterizedTest
@MethodSource("getFilterQuery")
void testFilterOne(final String text, final String queryString, final int numberOfResults)
throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, queryString);
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(numberOfResults, organizations.size(), text);
}
@ParameterizedTest
@MethodSource("getFilterQueryDerivedProperty")
@Tag(Assertions.CB_ONLY_TEST)
void testFilterOneDerivedProperty(final String text, final String queryString, final int numberOfResults)
throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, queryString);
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(numberOfResults, organizations.size(), text);
}
@ParameterizedTest
@MethodSource("getEnumQuery")
void testFilterEnum(final String text, final String queryString, final String result)
throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, queryString);
helper.assertStatus(200);
final ArrayNode persons = helper.getValues();
assertEquals(1, persons.size());
assertEquals(result, persons.get(0).get("ID").asText(), text);
}
@Test
void testFilterTwoAndEquals() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and CodeID eq 'NUTS2' and DivisionCode eq 'BE25'");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(1, organizations.size());
assertEquals("BEL", organizations.get(0).get("CountryCode").asText());
}
@Test
void testFilterAndOrEqualsParenthesis() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and (DivisionCode eq 'BE25' or DivisionCode eq 'BE24')&$orderby=DivisionCode desc");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(2, organizations.size());
assertEquals("BE25", organizations.get(0).get("DivisionCode").asText());
}
@Test
void testFilterAndOrEqualsNoParenthesis() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and DivisionCode eq 'BE25' or CodeID eq '3166-1'&$orderby=DivisionCode desc");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(5, organizations.size());
assertEquals("USA", organizations.get(0).get("DivisionCode").asText());
}
@Test
void testFilterAndWithFunction1() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and contains(tolower(DivisionCode),tolower('BE1'))&$orderby=DivisionCode asc");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(3, organizations.size());
assertEquals("BE1", organizations.get(0).get("DivisionCode").asText());
}
@Test
void testFilterAndWithFunction2() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and contains(DivisionCode,'BE1')&$orderby=DivisionCode asc");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(3, organizations.size());
assertEquals("BE1", organizations.get(0).get("DivisionCode").asText());
}
@Test
void testFilterAndWithComparisonContainingFunction() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and tolower(DivisionCode) eq tolower('BE1')");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(1, organizations.size());
assertEquals("BE1", organizations.get(0).get("DivisionCode").asText());
}
@Test
void testFilterComparisonViaNavigationContainingFunction() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles?$filter=tolower(Organization/Name1) eq 'third org.'");
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(3, act.size());
}
@Test
void testFilterComparisonTwoFunctionsContainingNavigationNotSupported() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles?$filter=tolower(Organization/Name1) eq tolower(Organization/Name2)");
helper.assertStatus(501);
}
@Test
void testFilterComparisonViaNavigationContainingNestedFunctionNotSupported() throws IOException,
ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles?$filter=contains(tolower(Organization/Name1), 'third org.')");
helper.assertStatus(501);
}
// Usage of mult currently creates parser error: The types 'Edm.Double' and '[Int64, Int32, Int16, Byte, SByte]' are
// not compatible.
@Disabled("Usage of mult currently creates parser error")
@Test
void testFilterSubstringStartCalculated() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,2 mul 3) eq 'Dakota'");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(2, organizations.size());
}
@Test
void testFilterNavigationPropertyToManyValueAnyProtected() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Willi"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$filter=Roles/any(d:d/RoleCategory eq 'X')", claims);
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(2, organizations.size());
}
@Test
void testFilterNavigationPropertyToManyValueAnyProtectedThrowsErrorOnMissingClaim() throws IOException,
ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Willi"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$filter=RolesProtected/any(d:d/RoleCategory eq 'X')", claims);
helper.assertStatus(403);
}
@Test
void testFilterNavigationPropertyToManyValueAnyProtectedDeep() throws IOException,
ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Willi"));
claims.add("RoleCategory", new JPAClaimsPair<>("C"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$filter=RolesProtected/any(d:d/RoleCategory eq 'X')", claims);
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(0, act.size());
}
@Test
void testFilterNavigationStartsWithAll() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$filter=InhouseAddress/all(d:startswith(d/TaskID, 'D'))");
helper.assertStatus(200);
final ArrayNode person = helper.getValues();
assertEquals(1, person.size());
assertEquals("97", person.get(0).get("ID").asText());
}
@Test
void testFilterCountNavigationPropertyProtectedAllResults() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("*"));
claims.add("RoleCategory", new JPAClaimsPair<>("A"));
claims.add("RoleCategory", new JPAClaimsPair<>("C"));
IntegrationTestHelper helper;
helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID&$filter=RolesProtected/$count ge 2", claims);
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(2, act.size());
}
@Test
void testFilterCountNavigationPropertyProtected() throws IOException, ODataException {
// https://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398301
// Example 43: return all Categories with less than 10 products
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
claims.add("RoleCategory", new JPAClaimsPair<>("A", "B"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID&$filter=RolesProtected/$count ge 2", claims); // and ID eq '3'
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(1, act.size());
assertEquals("3", act.get(0).get("ID").asText());
}
@Test
void testFilterCountNavigationPropertyProtectedThrowsErrorOnMissingClaim() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID&$filter=RolesProtected/$count ge 2", claims);
helper.assertStatus(403);
}
@Test
void testFilterNavigationPropertyContainsProtectedDeep() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("*"));
claims.add("RoleCategory", new JPAClaimsPair<>("Z"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoleProtecteds?$filter=contains(BupaPartnerProtected/Name1, 'o')", claims);
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(0, organizations.size());
}
@Test
void testFilterNavigationPropertyEqualsProtectedDeep() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Willi"));
claims.add("RoleCategory", new JPAClaimsPair<>("*"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoleProtecteds?$filter=BupaPartnerProtected/Type eq '1'", claims);
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
assertEquals(3, organizations.size());
}
@Test
void testFilterNavigationPropertyAndExpandThatNavigationProperty() throws IOException,
ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=Parent/DivisionCode eq 'BE2'&$expand=Parent");
helper.assertStatus(200);
final ArrayNode admin = helper.getValues();
assertEquals(5, admin.size());
assertNotNull(admin.get(3).findValue("Parent"));
assertFalse(admin.get(3).findValue("Parent") instanceof NullNode);
assertEquals("BE2", admin.get(3).findValue("Parent").get("DivisionCode").asText());
}
@Test
void testFilterNavigationPropertyViaJoinTableSubtype() throws IOException,
ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$select=ID&$filter=SupportedOrganizations/any()");
helper.assertStatus(200);
final ArrayNode admin = helper.getValues();
assertEquals(2, admin.size());
assertEquals("98", admin.get(0).findValue("ID").asText());
}
@Disabled // EclipseLinkProblem see https://bugs.eclipse.org/bugs/show_bug.cgi?id=529565
@Test
void testFilterNavigationPropertyViaJoinTableCountSubType() throws IOException, // NOSONAR
ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$select=ID&$filter=SupportedOrganizations/$count gt 1");
helper.assertStatus(200);
final ArrayNode admin = helper.getValues();
assertEquals(2, admin.size());
assertEquals("98", admin.get(0).findValue("ID").asText());
}
@Test
void testFilterMappedNavigationPropertyViaJoinTableSubtype() throws IOException,
ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$select=Name1&$filter=SupportEngineers/any(d:d/LastName eq 'Doe')");
helper.assertStatus(200);
final ArrayNode admin = helper.getValues();
assertEquals(1, admin.size());
assertEquals("First Org.", admin.get(0).findValue("Name1").asText());
}
@Tag(Assertions.CB_ONLY_TEST)
@Test
void testFilterNavigationPropertyViaJoinTableCount() throws IOException,
ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$filter=Teams/$count eq 0&$select=ID");
helper.assertStatus(200);
final ArrayNode admin = helper.getValues();
assertEquals(1, admin.size());
assertEquals("98", admin.get(0).findValue("ID").asText());
}
@Test
void testFilterMappedNavigationPropertyViaJoinTableFilter() throws IOException,
ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Teams?$select=Name&$filter=Member/any(d:d/LastName eq 'Mustermann')");
helper.assertStatus(200);
final ArrayNode admin = helper.getValues();
assertEquals(2, admin.size());
}
@Test
void testFilterWithAllExpand() throws ODataException, IOException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$filter=Name1 eq 'Third Org.'&$expand=Roles");
helper.assertStatus(200);
final ArrayNode organization = helper.getValues();
assertNotNull(organization);
assertEquals(1, organization.size());
assertEquals(3, organization.get(0).get("Roles").size());
}
@Test
void testExpandWithFilterOnCollectionAttribute() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$expand=SupportEngineers($filter=InhouseAddress/any(p:p/Building eq '2'))");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
for (final JsonNode organization : organizations) {
if (organization.get("ID").asText().equals("1") || organization.get("ID").asText().equals("2")) {
final ArrayNode supportEngineers = (ArrayNode) organization.get("SupportEngineers");
assertEquals(1, supportEngineers.size());
final ArrayNode address = (ArrayNode) supportEngineers.get(0).get("InhouseAddress");
assertEquals(1, address.size());
assertEquals("2", address.get(0).get("Building").asText());
} else {
final ArrayNode supportEngineers = (ArrayNode) organization.get("SupportEngineers");
assertEquals(0, supportEngineers.size());
}
}
}
@Test
void testAnyFilterOnExpandWithMultipleHops() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | true |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPACountExpressionTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPACountExpressionTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
class JPACountExpressionTest {
private JPACountExpression cut;
private Literal literal;
private BinaryOperatorKind operator;
private Member member;
@BeforeEach
void setup() {
literal = mock(Literal.class);
member = mock(Member.class);
}
@Test
void checkGetMember() throws ODataJPAFilterException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
operator = BinaryOperatorKind.EQ;
cut = new JPACountExpression(member, literal, operator);
assertEquals(uriInfo, cut.getMember());
}
@Test
void checkIsInvertedDefaultFalse() throws ODataJPAFilterException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
operator = BinaryOperatorKind.EQ;
cut = new JPACountExpression(member, literal, operator);
assertFalse(cut.isInversionRequired());
assertEquals(BinaryOperatorKind.EQ, cut.getOperator());
}
@Test
void checkIsInvertedTrueEqZero() throws ODataJPAFilterException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
when(literal.getType()).thenReturn(EdmInt32.getInstance());
when(literal.getText()).thenReturn("0");
operator = BinaryOperatorKind.EQ;
cut = new JPACountExpression(member, literal, operator);
assertTrue(cut.isInversionRequired());
assertEquals(BinaryOperatorKind.NE, cut.getOperator());
}
@Test
void checkIsInvertedTrueLeZero() throws ODataJPAFilterException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
when(literal.getType()).thenReturn(EdmInt32.getInstance());
when(literal.getText()).thenReturn("0");
operator = BinaryOperatorKind.LE;
cut = new JPACountExpression(member, literal, operator);
assertTrue(cut.isInversionRequired());
assertEquals(BinaryOperatorKind.NE, cut.getOperator());
}
@Test
void checkIsInvertedFalseGtZero() throws ODataJPAFilterException {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
when(literal.getType()).thenReturn(EdmInt32.getInstance());
when(literal.getText()).thenReturn("0");
operator = BinaryOperatorKind.GT;
cut = new JPACountExpression(member, literal, operator);
assertFalse(cut.isInversionRequired());
assertEquals(BinaryOperatorKind.GT, cut.getOperator());
}
@Test
void checkAcceptsVisitor() throws ExpressionVisitException, ODataApplicationException {
@SuppressWarnings("unchecked")
final ExpressionVisitor<String> visitor = mock(ExpressionVisitor.class);
when(visitor.visitBinaryOperator(eq(BinaryOperatorKind.GT), anyString(), anyString())).thenReturn("Hello");
when(visitor.visitLiteral(literal)).thenReturn("0");
when(visitor.visitMember(member)).thenReturn("Test");
when(literal.getText()).thenReturn("0");
operator = BinaryOperatorKind.GT;
cut = new JPACountExpression(member, literal, operator);
assertEquals("Hello", cut.accept(visitor));
verify(visitor).visitMember(member);
verify(visitor).visitLiteral(literal);
verify(visitor).visitBinaryOperator(eq(BinaryOperatorKind.GT), anyString(), anyString());
}
@Test
void checkGeZeroNotSupported() {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
when(member.getResourcePath()).thenReturn(uriInfo);
when(literal.getType()).thenReturn(EdmInt32.getInstance());
when(literal.getText()).thenReturn("0");
operator = BinaryOperatorKind.GE;
assertThrows(ODataJPAFilterException.class, () -> new JPACountExpression(member, literal, operator));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPANavigationOperationTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPANavigationOperationTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.apache.olingo.server.api.uri.queryoption.expression.MethodKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataServiceContext;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
class JPANavigationOperationTest {
private JPANavigationOperation cut;
private JPAFilterComplierAccess jpaComplier;
private MethodKind methodCall;
private List<JPAOperator> parameters;
private JPAMemberOperator operator;
private JPAOperationConverter converter;
private JPAODataDatabaseOperations dbOperations;
private CriteriaBuilder cb;
@BeforeEach
void setup() throws ODataException {
final JPAODataQueryDirectives directives = JPAODataServiceContext.with()
.useQueryDirectives()
.build()
.build()
.getQueryDirectives();
jpaComplier = mock(JPAFilterComplierAccess.class);
operator = mock(JPAMemberOperator.class);
dbOperations = mock(JPAODataDatabaseOperations.class);
methodCall = MethodKind.INDEXOF;
cb = mock(CriteriaBuilder.class);
parameters = new ArrayList<>();
parameters.add(operator);
converter = new JPAOperationConverter(cb, dbOperations, directives);
when(jpaComplier.getConverter()).thenReturn(converter);
cut = new JPANavigationOperation(jpaComplier, methodCall, parameters);
}
@Test
void testCreateParameterOneLiteral() {
final JPALiteralOperator literal = mock(JPALiteralOperator.class);
parameters.add(0, literal);
assertDoesNotThrow(() -> new JPANavigationOperation(jpaComplier, methodCall, parameters));
}
@Test
void testGetNameOfMethod() {
assertEquals(methodCall.name(), cut.getName());
}
@Test
void testToStringContainsMethodCall() {
assertTrue(cut.toString().contains(methodCall.toString()));
}
@Test
void testReturnNullOfSubMember() {
final Member act = cut.getMember();
assertNotNull(act);
}
@TestFactory
Stream<DynamicTest> testMemberMethodsReturningNull() {
final Member act = cut.getMember();
return Stream.of("getStartTypeFilter", "getType")
.map(method -> dynamicTest(method, () -> assertNull(executeMethod(act, method))));
}
@Test
void testMemberAcceptReturnsNull() throws ExpressionVisitException, ODataApplicationException {
assertNull(cut.getMember().accept(null));
}
@Test
void testMemberIsCollectionFalse() {
assertFalse(cut.getMember().isCollection());
}
@TestFactory
Stream<DynamicTest> testMemberResourceMethodsReturningNull() {
final UriInfoResource act = cut.getMember().getResourcePath();
return Stream.of("getApplyOption", "getCountOption", "getDeltaTokenOption", "getExpandOption", "getFilterOption",
"getFormatOption", "getIdOption", "getOrderByOption", "getSearchOption", "getSelectOption", "getSkipOption",
"getSkipTokenOption", "getTopOption")
.map(method -> dynamicTest(method, () -> assertNull(executeMethod(act, method))));
}
@Test
void testMemberResourceGetValueForAliasNull() {
assertNull(cut.getMember().getResourcePath().getValueForAlias("Test"));
}
@Test
void testMemberResourceGetCustomQueryOptionReturnsEmptyList() {
final List<CustomQueryOption> act = cut.getMember().getResourcePath().getCustomQueryOptions();
assertNotNull(act);
assertTrue(act.isEmpty());
}
@TestFactory
Stream<DynamicTest> testMethodsReturningNull() {
return Stream.of("getOperator")
.map(method -> dynamicTest(method, () -> assertNull(executeMethod(cut, method))));
}
private Object executeMethod(final Object object, final String methodName) {
final Class<?> clazz = object.getClass();
try {
final Method method = clazz.getMethod(methodName);
return method.invoke(object);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
fail();
}
return "Test";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestScalarDbFunctions.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestScalarDbFunctions.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
class TestScalarDbFunctions {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
protected static EntityManagerFactory emf;
protected Map<String, List<String>> headers;
protected static JPADefaultEdmNameBuilder nameBuilder;
protected static DataSource ds;
@BeforeAll
public static void setupClass() {
ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
}
@Test
void testFilterOnFunctionAndProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=$it/Area,Population=$it/Population) mul 1000000 gt 1000 and ParentDivisionCode eq 'BE255'&orderBy=DivisionCode)");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(2, orgs.size());
assertEquals("35002", orgs.get(0).get("DivisionCode").asText());
}
@Test
void testFilterOnFunction() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=$it/Area,Population=$it/Population) gt 1");
helper.assertStatus(200);
}
private static Stream<Arguments> provideFunctionQueries() {
return Stream.of(
arguments("FunctionAndMultiply",
"AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=Area,Population=Population) mul 1000000 gt 100",
59),
arguments("FunctionWithFixedValue",
"AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=13079087,Population=$it/Population) mul 1000000 gt 1000",
29),
arguments("FunctionComputedValue",
"AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=Area div 1000000,Population=Population) gt 1000",
7),
arguments("FunctionMixParamOrder",
"AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Population=Population,Area=Area) mul 1000000 gt 1000",
7),
arguments("FunctionMixParamOrder",
"AdministrativeDivisions?$filter=com.sap.olingo.jpa.ConvertToQkm(Area=$it/Area) gt 100",
4));
}
@ParameterizedTest
@MethodSource("provideFunctionQueries")
void testFilterOnFunctionAndMultiply(final String text, final String queryString, final int numberOfResults)
throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, queryString);
helper.assertStatus(200);
final ArrayNode divisions = helper.getValues();
assertEquals(numberOfResults, divisions.size(), text);
}
@Test
void testFilterOnFunctionNested() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"""
AdministrativeDivisions?$filter=\
com.sap.olingo.jpa.PopulationDensity(Area=\
com.sap.olingo.jpa.ConvertToQkm(Area=$it/Area),Population=$it/Population) gt 1000""");
helper.assertStatus(200);
final ArrayNode jobs = helper.getValues();
assertEquals(7, jobs.size());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPALiteralOperator.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPALiteralOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.stream.Stream;
import org.apache.olingo.commons.core.edm.primitivetype.SingletonPrimitiveType;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.reflections8.Reflections;
import org.reflections8.scanners.SubTypesScanner;
import org.reflections8.util.ConfigurationBuilder;
class TestJPALiteralOperator {
private static OData odata = OData.newInstance();
@TestFactory
Stream<DynamicTest> testNonGeometryPrimitiveTypeAreConverted() {
final ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setScanners(new SubTypesScanner(false));
configBuilder.forPackages(SingletonPrimitiveType.class.getPackage().getName());
final Reflections refection = new Reflections(configBuilder);
final Set<Class<? extends SingletonPrimitiveType>> edmPrimitiveTypes = refection.getSubTypesOf(
SingletonPrimitiveType.class);
return edmPrimitiveTypes
.stream()
.filter(t -> t.getSuperclass() == SingletonPrimitiveType.class)
.map(TestJPALiteralOperator::createEdmPrimitiveType)
.filter(i -> i != null)
.map(TestJPALiteralOperator::createLiteralOperator)
.map(operator -> dynamicTest(operator.getLiteral().getType().getName(), () -> assertTypeConversion(operator)));
}
private void assertTypeConversion(final JPALiteralOperator operator) throws ODataApplicationException {
final Object act = operator.get();
assertNotNull(act);
assertFalse(act.toString().contains("'"));
}
private static SingletonPrimitiveType createEdmPrimitiveType(
final Class<? extends SingletonPrimitiveType> typeClass) {
try {
final Method m = typeClass.getMethod("getInstance");
return (SingletonPrimitiveType) m.invoke(null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
| SecurityException e) {
return null;
}
}
private static JPALiteralOperator createLiteralOperator(final SingletonPrimitiveType typeInstance) {
final Literal l = mock(Literal.class);
when(l.getType()).thenReturn(typeInstance);
when(l.getText()).thenReturn(determineLiteral(typeInstance));
return new JPALiteralOperator(odata, l);
}
private static String determineLiteral(final SingletonPrimitiveType typeInstance) {
switch (typeInstance.getName()) {
case "Guid":
return "819a3e3b-837e-4ecb-a600-654ef7b5aace";
case "Date":
return "2021-10-01";
case "Boolean":
return "true";
case "TimeOfDay":
return "10:00:12.10";
case "DateTimeOffset":
return "2021-10-01T10:00:12Z";
case "Duration":
return "P2DT12H30M5S";
default:
return "123";
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationNullQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationNullQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterExpression;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRoleProtected;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
class JPANavigationNullQueryTest extends TestBase {
private JPANavigationSubQuery cut;
private TestHelper helper;
private EntityManager em;
private OData odata;
private UriResourceNavigation uriResourceItem;
private JPAAbstractQuery parent;
private JPAAssociationPath association;
private From<?, ?> from;
private Root<BusinessPartnerProtected> queryRoot;
private JPAODataClaimProvider claimsProvider;
private JPAEntityType jpaEntityType;
@SuppressWarnings("rawtypes")
private CriteriaQuery cq;
private CriteriaBuilder cb;
private Subquery<Object> subQuery;
private JPAODataRequestContextAccess requestContext;
@SuppressWarnings("unchecked")
@BeforeEach
void setup() throws ODataException {
helper = getHelper();
em = mock(EntityManager.class);
parent = mock(JPAAbstractQuery.class);
association = helper.getJPAAssociationPath(BusinessPartnerRoleProtected.class, "BupaPartnerProtected");
claimsProvider = mock(JPAODataClaimProvider.class);
odata = OData.newInstance();
uriResourceItem = mock(UriResourceNavigation.class);
jpaEntityType = helper.getJPAEntityType(BusinessPartnerProtected.class);
cq = mock(CriteriaQuery.class);
cb = mock(CriteriaBuilder.class);
subQuery = mock(Subquery.class);
queryRoot = mock(Root.class);
from = mock(From.class);
requestContext = mock(JPAODataRequestContextAccess.class);
final UriParameter key = mock(UriParameter.class);
when(em.getCriteriaBuilder()).thenReturn(cb);
when(uriResourceItem.getKeyPredicates()).thenReturn(Collections.singletonList(key));
when(parent.getQuery()).thenReturn(cq);
when(cq.subquery(any(Class.class))).thenReturn(subQuery);
when(subQuery.from(BusinessPartnerProtected.class)).thenReturn(queryRoot);
when(claimsProvider.get("UserId")).thenReturn(Collections.singletonList(new JPAClaimsPair<>("Willi")));
doReturn(BusinessPartnerProtected.class).when(from).getJavaType();
}
@Test
void testCutExists() throws ODataApplicationException {
cut = new JPANavigationNullQuery(odata, helper.sd, jpaEntityType, em, parent, from, association, Optional.of(
claimsProvider), Collections.emptyList());
assertNotNull(cut);
}
@Test
void testGetSubQueryThrowsExceptionWhenChildQueryProvided() throws ODataApplicationException {
cut = new JPANavigationNullQuery(odata, helper.sd, jpaEntityType, em, parent, from, association, Optional.of(
claimsProvider), Collections.emptyList());
assertThrows(ODataJPAQueryException.class, () -> cut.getSubQuery(subQuery, null, Collections.emptyList()));
}
@SuppressWarnings("unchecked")
@Test
void testJoinQueryAggregateWithClaim() throws ODataApplicationException, ODataJPAModelException,
EdmPrimitiveTypeException {
final Member member = mock(Member.class);
final UriInfoResource uriInfoResource = mock(UriInfoResource.class);
final Literal literal = mock(Literal.class);
final EdmPrimitiveType edmType = mock(EdmPrimitiveType.class);
final JPAFilterExpression expression = new JPAFilterExpression(member, literal, BinaryOperatorKind.EQ);
final JPAODataDatabaseOperations converterExtension = mock(JPAODataDatabaseOperations.class);
final Path<Object> userNamePath = mock(Path.class);
final Path<Object> idPath = mock(Path.class);
final Predicate equalExpression1 = mock(Predicate.class);
when(parent.getContext()).thenReturn(requestContext);
when(parent.getJpaEntity()).thenReturn(helper.getJPAEntityType(BusinessPartnerRoleProtected.class));
when(requestContext.getOperationConverter()).thenReturn(converterExtension);
when(member.getResourcePath()).thenReturn(uriInfoResource);
when(literal.getText()).thenReturn("1");
when(literal.getType()).thenReturn(edmType);
when(edmType.valueOfString(any(), any(), any(), any(), any(), any(), any())).thenReturn(Integer.valueOf(1));
when(queryRoot.get("userName")).thenReturn(userNamePath);
when(queryRoot.get("iD")).thenReturn(idPath);
when(from.get("businessPartnerID")).thenReturn(idPath);
when(cb.equal(idPath, idPath)).thenReturn(equalExpression1);
cut = new JPANavigationNullQuery(odata, helper.sd, jpaEntityType, em, parent, from, association, Optional.of(
claimsProvider), Collections.emptyList());
cut.buildExpression(expression, Collections.emptyList());
cut.getSubQuery(null, null, Collections.emptyList());
assertNotNull(cut);
verify(cb).equal(idPath, idPath);
verify(cb).equal(userNamePath, "Willi");
}
@Test
void testCreateWhereEnhancementReturnsNull() throws ODataApplicationException {
cut = new JPANavigationNullQuery(odata, helper.sd, jpaEntityType, em, parent, from, association, Optional.of(
claimsProvider), Collections.emptyList());
assertNull(cut.createWhereEnhancement(jpaEntityType, from));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandSubQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandSubQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.mockito.Mockito.when;
import java.lang.reflect.InvocationTargetException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.junit.jupiter.api.Tag;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.core.util.Assertions;
@Tag(Assertions.CB_ONLY_TEST)
class JPAExpandSubQueryTest extends JPAExpandQueryTest {
@Override
protected JPAExpandQuery createCut(final JPAInlineItemInfo item) throws ODataException {
try {
final var clazz = Class.forName("com.sap.olingo.jpa.processor.cb.api.EntityManagerFactoryWrapper");
final var constructor = clazz.getConstructor(EntityManagerFactory.class, JPAServiceDocument.class,
ProcessorSqlPatternProvider.class);
final var wrapper = constructor.newInstance(emf, helper.sd, null);
final var createMethod = clazz.getMethod("createEntityManager");
final var em = createMethod.invoke(wrapper);
when(requestContext.getEntityManager()).thenReturn((EntityManager) em);
return new JPAExpandSubQuery(OData.newInstance(), item, requestContext);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException
| InvocationTargetException | InstantiationException | IllegalArgumentException e) {
throw new ODataException(e);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Stream;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.AbstractQuery;
import jakarta.persistence.criteria.From;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.queryoption.OrderByItem;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.apply.AggregateExpression;
import org.apache.olingo.server.api.uri.queryoption.expression.Alias;
import org.apache.olingo.server.api.uri.queryoption.expression.Binary;
import org.apache.olingo.server.api.uri.queryoption.expression.Enumeration;
import org.apache.olingo.server.api.uri.queryoption.expression.Expression;
import org.apache.olingo.server.api.uri.queryoption.expression.LambdaRef;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Method;
import org.apache.olingo.server.api.uri.queryoption.expression.TypeLiteral;
import org.apache.olingo.server.api.uri.queryoption.expression.Unary;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.util.TestQueryBase;
class JPAAbstractQueryTest extends TestQueryBase {
private JPAAbstractQuery cut;
private EntityManager em;
@Override
@BeforeEach
public void setup() throws ODataException, ODataJPAIllegalAccessException {
super.setup();
em = mock(EntityManager.class);
cut = new Query(null, helper.sd, jpaEntityType, em, Optional.empty());
}
static Stream<Expression> expressionProvider() {
return Stream.of(
mock(Method.class),
mock(Literal.class),
mock(TypeLiteral.class),
mock(Unary.class),
mock(LambdaRef.class),
mock(Enumeration.class),
mock(Binary.class),
mock(Alias.class),
mock(AggregateExpression.class));
}
@MethodSource("expressionProvider")
@ParameterizedTest
void testExtractOrderByNavigationAttributesThrowsExceptionIfNotSupported(final Expression orderByExpression) {
final OrderByOption orderBy = mock(OrderByOption.class);
final OrderByItem item = mock(OrderByItem.class);
when(orderBy.getOrders()).thenReturn(Collections.singletonList(item));
when(item.getExpression()).thenReturn(orderByExpression);
assertThrows(ODataJPAQueryException.class, () -> cut.getOrderByAttributes(orderBy));
}
private static class Query extends JPAAbstractQuery {
Query(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntityType, final EntityManager em,
final Optional<JPAODataClaimProvider> claimsProvider) {
super(odata, sd, jpaEntityType, em, claimsProvider);
}
@Override
public <T> AbstractQuery<T> getQuery() {
throw new IllegalAccessError();
}
@Override
public <S, T> From<S, T> getRoot() {
throw new IllegalAccessError();
}
@Override
protected Locale getLocale() {
return Locale.CANADA_FRENCH;
}
@Override
JPAODataRequestContextAccess getContext() {
throw new IllegalAccessError();
}
@Override
protected jakarta.persistence.criteria.Expression<Boolean> createWhereEnhancement(final JPAEntityType et,
final From<?, ?> from)
throws ODataJPAProcessorException {
return null;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandJoinCountQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandJoinCountQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.processor.JPAEmptyDebugger;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class JPAExpandJoinCountQueryTest extends TestBase {
private JPAExpandJoinCountQuery cut;
private OData odata;
private JPAODataRequestContextAccess requestContext;
private JPAEdmProvider edmProvider;
private JPAServiceDocument sd;
private JPAEntityType et;
private JPAAssociationPath association;
private List<JPANavigationPropertyInfo> hops;
private Optional<JPAKeyBoundary> keyBoundary;
@BeforeEach
void setup() throws ODataException {
odata = OData.newInstance();
edmProvider = mock(JPAEdmProvider.class);
sd = mock(JPAServiceDocument.class);
requestContext = mock(JPAODataRequestContextAccess.class);
et = mock(JPAEntityType.class);
association = mock(JPAAssociationPath.class);
hops = new ArrayList<>();
keyBoundary = Optional.empty();
when(edmProvider.getServiceDocument()).thenReturn(sd);
when(requestContext.getEntityManager()).thenReturn(emf.createEntityManager());
when(requestContext.getDebugger()).thenReturn(new JPAEmptyDebugger());
when(requestContext.getEdmProvider()).thenReturn(edmProvider);
}
@Test
void testCreateCountQuery() {
assertDoesNotThrow(() -> new JPAExpandJoinCountQuery(odata, requestContext, et, association, hops,
keyBoundary));
}
@Test
void testConvertCountResultCanHandleInteger() throws ODataException {
final List<Tuple> intermediateResult = new ArrayList<>();
final Tuple row = mock(Tuple.class);
when(row.get(JPAAbstractQuery.COUNT_COLUMN_NAME)).thenReturn(Integer.valueOf(5));
intermediateResult.add(row);
cut = new JPAExpandJoinCountQuery(odata, requestContext, et, association, hops, keyBoundary);
final Map<String, Long> act = cut.convertCountResult(intermediateResult);
assertNotNull(act);
assertEquals(1, act.size());
assertEquals(5L, act.get(""));
}
@Test
void testConvertCountResultCanHandleLong() throws ODataException {
final List<Tuple> intermediateResult = new ArrayList<>();
final Tuple row = mock(Tuple.class);
when(row.get(JPAAbstractQuery.COUNT_COLUMN_NAME)).thenReturn(Long.valueOf(5));
intermediateResult.add(row);
cut = new JPAExpandJoinCountQuery(odata, requestContext, et, association, hops, keyBoundary);
final Map<String, Long> act = cut.convertCountResult(intermediateResult);
assertNotNull(act);
assertEquals(1, act.size());
assertEquals(5L, act.get(""));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemWrapperTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemWrapperTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.mockito.Mockito.mock;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.junit.jupiter.api.BeforeEach;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
class JPAExpandItemWrapperTest extends JPAExpandItemPageableTest {
private JPAExpandItemWrapper cut;
@BeforeEach
void setup() {
et = mock(JPAEntityType.class);
expandItem = mock(ExpandItem.class);
cut = new JPAExpandItemWrapper(expandItem, et);
}
@Override
JPAExpandItemPageable getCut() {
return cut;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestSelectionPathInfo.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestSelectionPathInfo.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class TestSelectionPathInfo {
private SelectionPathInfo<Integer> cut;
@Test
void testSetTripleEmptySets() {
cut = new SelectionPathInfo<>(new HashSet<>(), new HashSet<>(), new HashSet<>());
assertNotNull(cut);
assertNotNull(cut.getODataSelections());
assertNotNull(cut.getRequiredSelections());
assertNotNull(cut.getTransientSelections());
assertNotNull(cut.joined());
}
@Test
void testSetTripleFirstNull() {
cut = new SelectionPathInfo<>(null, new HashSet<>(), new HashSet<>());
assertNotNull(cut);
assertNotNull(cut.getODataSelections());
assertNotNull(cut.getRequiredSelections());
assertNotNull(cut.getTransientSelections());
assertNotNull(cut.joined());
}
@Test
void testSetTripleSecondNull() {
cut = new SelectionPathInfo<>(new HashSet<>(), null, new HashSet<>());
assertNotNull(cut);
assertNotNull(cut.getODataSelections());
assertNotNull(cut.getRequiredSelections());
assertNotNull(cut.getTransientSelections());
assertNotNull(cut.joined());
}
@Test
void testSetTripleThirdNull() {
cut = new SelectionPathInfo<>(new HashSet<>(), new HashSet<>(), null);
assertNotNull(cut);
assertNotNull(cut.getODataSelections());
assertNotNull(cut.getRequiredSelections());
assertNotNull(cut.getTransientSelections());
assertNotNull(cut.joined());
}
@Test
void testJoinedDoesNotReturnDuplicates() {
final Set<Integer> first = new HashSet<>(Arrays.asList(1, 3, 5, 7, 9, 2));
final Set<Integer> second = new HashSet<>(Arrays.asList(1, 4, 6, 2));
final Set<Integer> third = new HashSet<>(Arrays.asList(7, 8));
final Set<Integer> exp = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
cut = new SelectionPathInfo<>(first, second, third);
assertNotNull(cut);
assertEquals(exp, cut.joined());
}
@Test
void testJoinedPersistentDoesNotReturnTransient() {
final Set<Integer> first = new HashSet<>(Arrays.asList(1, 3, 5, 7, 9, 2));
final Set<Integer> second = new HashSet<>(Arrays.asList(1, 4, 6, 2));
final Set<Integer> third = new HashSet<>(Arrays.asList(7, 8));
final Set<Integer> exp = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 9));
cut = new SelectionPathInfo<>(first, second, third);
assertNotNull(cut);
assertEquals(exp, cut.joinedPersistent());
}
@Test
void testJoinedRequestedDoesNotReturnRequired() {
final Set<Integer> first = new HashSet<>(Arrays.asList(1, 3, 5, 7, 9, 2));
final Set<Integer> second = new HashSet<>(Arrays.asList(1, 4, 6, 2));
final Set<Integer> third = new HashSet<>(Arrays.asList(7, 8));
final Set<Integer> exp = new HashSet<>(Arrays.asList(1, 2, 3, 5, 7, 8, 9));
cut = new SelectionPathInfo<>(first, second, third);
assertNotNull(cut);
assertEquals(exp, cut.joinedRequested());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractSubQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractSubQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorSubquery;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
class JPAAbstractSubQueryTest extends TestBase {
private TestHelper helper;
private EntityManager em;
private OData odata;
private JPAAbstractQuery parent;
private JPAAssociationPath association;
private From<?, ?> from;
private Subquery<Object> subQuery;
private JPAAbstractSubQuery cut;
@SuppressWarnings("unchecked")
@BeforeEach
void setup() throws ODataException {
helper = getHelper();
em = mock(EntityManager.class);
parent = mock(JPAAbstractQuery.class);
association = helper.getJPAAssociationPath(BusinessPartnerProtected.class, "RolesJoinProtected");
odata = OData.newInstance();
from = mock(From.class);
subQuery = mock(Subquery.class);
cut = new JPASubQuery(odata, null, null, em, parent, from, association);
}
static Stream<Arguments> selectClauseParameter() {
return Stream.of(
arguments(false, new String[] { "ID" }),
arguments(true, new String[] { "ID" }),
arguments(false, new String[] { "ID", "ParentID" }));
}
@SuppressWarnings("unchecked")
@ParameterizedTest
@MethodSource("selectClauseParameter")
void testCreateSelectClauseJoinForExpand(final boolean forInExpression, final String[] attributes) {
final JPAPath jpaPath = createJpaPath(attributes[0]);
final Path<Object> path = mock(Path.class);
final List<JPAPath> conditionItems = Arrays.asList(jpaPath);
when(from.get(attributes[0])).thenReturn(path);
cut.createSelectClauseJoin(subQuery, from, conditionItems, forInExpression);
verify(subQuery).select(path);
}
@SuppressWarnings("unchecked")
@Test
void testCreateSelectClauseJoinForExpandInProcessor() {
final ProcessorSubquery<Object> subQuery = mock(ProcessorSubquery.class);
final JPAPath jpaPathId = createJpaPath("ID");
final JPAPath jpaPathParent = createJpaPath("ParentID");
final Path<Object> pathId = mock(Path.class);
final Path<Object> pathParent = mock(Path.class);
final List<JPAPath> conditionItems = Arrays.asList(jpaPathId, jpaPathParent);
when(from.get("ID")).thenReturn(pathId);
when(from.get("ParentID")).thenReturn(pathParent);
cut.createSelectClauseJoin(subQuery, from, conditionItems, true);
verify(subQuery).multiselect(Arrays.asList(pathId, pathParent));
}
@SuppressWarnings("unchecked")
@Test
void testCreateSelectClauseJoinForExpandInThrowsExceptionStandard() {
final JPAPath jpaPathId = createJpaPath("ID");
final JPAPath jpaPathParent = createJpaPath("ParentID");
final Path<Object> pathId = mock(Path.class);
final Path<Object> pathParent = mock(Path.class);
final List<JPAPath> conditionItems = Arrays.asList(jpaPathId, jpaPathParent);
when(from.get("ID")).thenReturn(pathId);
when(from.get("ParentID")).thenReturn(pathParent);
assertThrows(IllegalStateException.class, () -> cut.createSelectClauseJoin(subQuery, from, conditionItems, true));
}
@SuppressWarnings("unchecked")
@ParameterizedTest
@MethodSource("selectClauseParameter")
void testCreateSelectClauseJoinAggregationExpand(final boolean forInExpression, final String[] attributes) {
final JPAPath jpaPath = createJpaPath(attributes[0]);
final Path<Object> path = mock(Path.class);
final JPAOnConditionItem item = mock(JPAOnConditionItem.class);
final List<JPAOnConditionItem> conditionItems = Arrays.asList(item);
when(item.getRightPath()).thenReturn(jpaPath);
when(from.get(attributes[0])).thenReturn(path);
cut.createSelectClauseAggregation(subQuery, from, conditionItems, forInExpression);
verify(subQuery).select(path);
}
@SuppressWarnings("unchecked")
@Test
void testCreateSelectClauseAggregationForExpandInProcessor() {
final ProcessorSubquery<Object> subQuery = mock(ProcessorSubquery.class);
final JPAPath jpaPathId = createJpaPath("ID");
final JPAPath jpaPathParent = createJpaPath("ParentID");
final Path<Object> pathId = mock(Path.class);
final Path<Object> pathParent = mock(Path.class);
final JPAOnConditionItem itemId = mock(JPAOnConditionItem.class);
final JPAOnConditionItem itemParent = mock(JPAOnConditionItem.class);
when(itemId.getRightPath()).thenReturn(jpaPathId);
when(itemParent.getRightPath()).thenReturn(jpaPathParent);
final List<JPAOnConditionItem> conditionItems = Arrays.asList(itemId, itemParent);
when(from.get("ID")).thenReturn(pathId);
when(from.get("ParentID")).thenReturn(pathParent);
cut.createSelectClauseAggregation(subQuery, from, conditionItems, true);
verify(subQuery).multiselect(Arrays.asList(pathId, pathParent));
}
@SuppressWarnings("unchecked")
@Test
void testCreateSelectClauseAggregationForExpandInThrowsExceptionStandard() {
final JPAPath jpaPathId = createJpaPath("ID");
final JPAPath jpaPathParent = createJpaPath("ParentID");
final Path<Object> pathId = mock(Path.class);
final Path<Object> pathParent = mock(Path.class);
final JPAOnConditionItem itemId = mock(JPAOnConditionItem.class);
final JPAOnConditionItem itemParent = mock(JPAOnConditionItem.class);
when(itemId.getRightPath()).thenReturn(jpaPathId);
when(itemParent.getRightPath()).thenReturn(jpaPathParent);
final List<JPAOnConditionItem> conditionItems = Arrays.asList(itemId, itemParent);
when(from.get("ID")).thenReturn(pathId);
when(from.get("ParentID")).thenReturn(pathParent);
assertThrows(IllegalStateException.class,
() -> cut.createSelectClauseAggregation(subQuery, from, conditionItems, true));
}
@Test
void isCollectionPropertyReturnsFalseForNavigation() {
assertFalse(cut.toCollectionProperty());
}
@Test
void isCollectionPropertyReturnsTrueForCollection() throws ODataJPAModelException {
final var attribute = helper.getJPAAttribute(Organization.class, "comment")
.map(a -> (JPACollectionAttribute) a)
.orElseGet(() -> fail());
cut = new JPASubQuery(odata, null, null, em, parent, from, attribute.asAssociation());
assertTrue(cut.toCollectionProperty());
}
private JPAPath createJpaPath(final String attribute) {
final JPAPath jpaPath = mock(JPAPath.class);
final JPAElement element = mock(JPAElement.class);
when(element.getInternalName()).thenReturn(attribute);
when(jpaPath.getPath()).thenReturn(Collections.singletonList(element));
return jpaPath;
}
private static class JPASubQuery extends JPAAbstractSubQuery {
JPASubQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntity, final EntityManager em,
final JPAAbstractQuery parent, final From<?, ?> from, final JPAAssociationPath association) {
super(odata, sd, jpaEntity, em, parent, from, association);
}
@Override
public <T> Subquery<T> getSubQuery(final Subquery<?> childQuery, final VisitableExpression expression,
final List<Path<Comparable<?>>> inPath)
throws ODataApplicationException {
return null;
}
@Override
public <S, T> From<S, T> getRoot() {
return null;
}
@Override
public List<Path<Comparable<?>>> getLeftPaths() throws ODataJPAIllegalAccessException {
return null;
}
@Override
protected Expression<Boolean> createWhereEnhancement(final JPAEntityType et, final From<?, ?> from)
throws ODataJPAProcessorException {
return null;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives.UuidSortOrder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole;
import com.sap.olingo.jpa.processor.core.testmodel.CurrentUser;
import com.sap.olingo.jpa.processor.core.testmodel.CurrentUserQueryExtension;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
abstract class JPAExpandQueryTest extends TestBase {
protected JPAExpandQuery cut;
protected EntityManager em;
protected JPAODataRequestContextAccess requestContext;
protected TestHelper helper;
protected JPAKeyPair organizationPair;
protected JPAKeyPair adminPair;
protected Optional<JPAKeyBoundary> organizationBoundary;
protected Optional<JPAKeyBoundary> adminBoundary;
@SuppressWarnings("rawtypes")
protected Map<JPAAttribute, Comparable> simpleKey;
private JPAODataQueryDirectives directives;
@BeforeEach
void setup() throws ODataException {
createHeaders();
helper = new TestHelper(emf, PUNIT_NAME);
em = emf.createEntityManager();
directives = new JPAODataQueryDirectives.JPAODataQueryDirectivesImpl(0, UuidSortOrder.AS_JAVA_UUID);
requestContext = mock(JPAODataRequestContextAccess.class);
organizationPair = new JPAKeyPair(helper.getJPAEntityType("Organizations").getKey(), directives);
organizationBoundary = Optional.of(new JPAKeyBoundary(1, organizationPair));
adminPair = new JPAKeyPair(helper.getJPAEntityType("AdministrativeDivisions").getKey(), directives);
adminBoundary = Optional.of(new JPAKeyBoundary(1, adminPair));
final JPAServiceDebugger debugger = mock(JPAServiceDebugger.class);
when(requestContext.getDebugger()).thenReturn(debugger);
when(requestContext.getClaimsProvider()).thenReturn(Optional.empty());
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getHeader()).thenReturn(mock(JPAHttpHeaderMap.class));
when(requestContext.getRequestParameter()).thenReturn(mock(JPARequestParameterMap.class));
when(requestContext.getEdmProvider()).thenReturn(helper.edmProvider);
when(requestContext.getOperationConverter()).thenReturn(new JPADefaultDatabaseProcessor());
}
@Test
void testSingletonSelectAllWithAllExpand() throws ODataException {
// .../CurrentUser?$expand=Roles&$format=json
final JPAInlineItemInfo item = createCurrentUserExpandRoles(Collections.emptyList());
cut = createCut(item);
final JPAExpandQueryResult act = cut.execute();
assertEquals(1, act.getNoResults());
}
@Test
void testSelectOrganizationByIdWithAllExpand() throws ODataException {
// .../Organizations('2')?$expand=Roles&$format=json
final UriParameter key = mock(UriParameter.class);
when(key.getName()).thenReturn("ID");
when(key.getText()).thenReturn("'2'");
final List<UriParameter> keyPredicates = new ArrayList<>();
keyPredicates.add(key);
final JPAInlineItemInfo item = createOrganizationExpandRoles(keyPredicates);
cut = createCut(item);
final JPAExpandQueryResult act = cut.execute();
assertEquals(1, act.getNoResults());
assertEquals(2, act.getNoResultsDeep());
}
@Test
void testExpandViaNavigation() throws ODataException {
// .../Persons('98')/SupportedOrganizations?$expand=Roles
final UriParameter key = mock(UriParameter.class);
when(key.getName()).thenReturn("ID");
when(key.getText()).thenReturn("'98'");
final List<UriParameter> keyPredicates = Collections.singletonList(key);
final JPAInlineItemInfo item = createPersonSupportedOrganizationsExpandRoles(keyPredicates);
cut = createCut(item);
final JPAExpandQueryResult act = cut.execute();
assertEquals(1, act.getNoResults());
assertNotNull(act.getResult("1"));
}
protected abstract JPAExpandQuery createCut(JPAInlineItemInfo item) throws ODataException;
protected JPAInlineItemInfo createOrganizationExpandRoles(final List<UriParameter> keyPredicates)
throws ODataJPAModelException,
ODataApplicationException {
final var et = helper.getJPAEntityType(Organization.class);
return createWithExpandRoles(keyPredicates, et, "Organizations");
}
protected JPAInlineItemInfo createCurrentUserExpandRoles(final List<UriParameter> keyPredicates)
throws ODataJPAModelException, ODataApplicationException {
final var et = helper.getJPAEntityType(CurrentUser.class);
final var provider = new CurrentUserQueryExtension();
when(requestContext.getQueryEnhancement(et)).thenReturn(Optional.of(provider));
return createWithExpandRoles(keyPredicates, et, "CurrentUser");
}
private JPAInlineItemInfo createPersonSupportedOrganizationsExpandRoles(final List<UriParameter> keyPredicates)
throws ODataJPAModelException, ODataApplicationException {
final var person = helper.getJPAEntityType(Person.class);
final var organization = helper.getJPAEntityType(Organization.class);
final var associationPath = organization.getAssociationPath("Roles");
final var supportedOrganizations = person.getAssociationPath("SupportedOrganizations");
final var roleNavigation = createUriResourceNavigation("Roles", "BusinessPartnerRole");
final var supportedOrganizationsNavigation = createUriResourceNavigation("SupportedOrganizations", organization
.getExternalName());
final var esResource = createEntitySetResource(keyPredicates, "Persons", person);
final var uriInfo = mock(UriInfoResource.class);
final var orderByOption = mock(OrderByOption.class);
when(uriInfo.getOrderByOption()).thenReturn(orderByOption);
when(uriInfo.getUriResourceParts()).thenReturn(Collections.singletonList(roleNavigation));
final var uriInfo2 = mock(UriInfoResource.class);
when(uriInfo2.getOrderByOption()).thenReturn(orderByOption);
when(uriInfo2.getUriResourceParts()).thenReturn(Arrays.asList(esResource, supportedOrganizationsNavigation));
final var hops = Arrays.asList(
new JPANavigationPropertyInfo(helper.sd, esResource, supportedOrganizations, null),
new JPANavigationPropertyInfo(helper.sd, associationPath, uriInfo2, organization),
new JPANavigationPropertyInfo(helper.sd, null, uriInfo, (JPAEntityType) associationPath.getTargetType()));
final JPAInlineItemInfo item = mock(JPAInlineItemInfo.class);
when(item.getExpandAssociation()).thenReturn(associationPath);
when(item.getEntityType()).thenReturn((JPAEntityType) associationPath.getTargetType());
when(item.getHops()).thenReturn(hops);
when(item.getUriInfo()).thenReturn(uriInfo);
return item;
}
private UriResourceNavigation createUriResourceNavigation(final String name, final String targetName) {
final var navigation = mock(UriResourceNavigation.class);
final var property = mock(EdmNavigationProperty.class);
final var edmType = mock(EdmEntityType.class);
when(navigation.getProperty()).thenReturn(property);
when(navigation.getType()).thenReturn(edmType);
when(property.getName()).thenReturn(name);
when(property.getType()).thenReturn(edmType);
when(edmType.getNamespace()).thenReturn(PUNIT_NAME);
when(edmType.getName()).thenReturn(targetName);
return navigation;
}
JPAInlineItemInfo createWithExpandRoles(final List<UriParameter> keyPredicates, final JPAEntityType parent,
final String esName) throws ODataJPAModelException, ODataApplicationException {
final JPAEntityType et = helper.getJPAEntityType(BusinessPartnerRole.class);
final JPAExpandItemWrapper uriExpandInfo = mock(JPAExpandItemWrapper.class);
JPANavigationPropertyInfo hop = createRoleNavigationPropertyInfo(keyPredicates, parent.getAssociationPath("Roles"),
esName, et);
final List<JPANavigationPropertyInfo> hops = new ArrayList<>();
hops.add(hop);
final JPAInlineItemInfo item = mock(JPAInlineItemInfo.class);
final UriResourceNavigation target = mock(UriResourceNavigation.class);
final EdmNavigationProperty targetProperty = mock(EdmNavigationProperty.class);
when(targetProperty.getName()).thenReturn("Roles");
when(target.getProperty()).thenReturn(targetProperty);
final List<UriResource> resourceParts = new ArrayList<>();
resourceParts.add(target);
hop = new JPANavigationPropertyInfo(helper.sd, null, uriExpandInfo, et);
hops.add(hop);
when(item.getEntityType()).thenReturn(et);
when(item.getUriInfo()).thenReturn(uriExpandInfo);
when(item.getHops()).thenReturn(hops);
when(item.getExpandAssociation()).thenReturn(parent.getAssociationPath("Roles"));
when(uriExpandInfo.getUriResourceParts()).thenReturn(resourceParts);
return item;
}
private JPANavigationPropertyInfo createRoleNavigationPropertyInfo(final List<UriParameter> keyPredicates,
final JPAAssociationPath jpaAssociationPath, final String esName, final JPAEntityType et)
throws ODataApplicationException {
final UriInfo uriInfo = mock(UriInfo.class);
final UriResourceEntitySet uriEs = createEntitySetResource(keyPredicates, esName, et);
when(uriInfo.getUriResourceParts()).thenReturn(Collections.singletonList(uriEs));
return new JPANavigationPropertyInfo(helper.sd, uriEs, jpaAssociationPath, uriInfo);
}
private UriResourceEntitySet createEntitySetResource(final List<UriParameter> keyPredicates, final String esName,
final JPAEntityType et) {
final UriResourceEntitySet uriEs = mock(UriResourceEntitySet.class);
when(uriEs.getKeyPredicates()).thenReturn(keyPredicates);
final EdmEntityType edmType = mock(EdmEntityType.class);
final EdmEntitySet edmSet = mock(EdmEntitySet.class);
when(uriEs.getType()).thenReturn(edmType);
when(uriEs.getEntitySet()).thenReturn(edmSet);
when(edmSet.getName()).thenReturn(esName);
when(edmType.getNamespace()).thenReturn(PUNIT_NAME);
when(edmType.getName()).thenReturn(et.getExternalName());
return uriEs;
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandLevelWrapperTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandLevelWrapperTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.FilterOption;
import org.apache.olingo.server.api.uri.queryoption.LevelsExpandOption;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SearchOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
class JPAExpandLevelWrapperTest extends JPAExpandItemPageableTest {
private static final String TEXT = "This is a text";
private static final String NAME = "Name";
private JPAExpandLevelWrapper cut;
private JPAServiceDocument sd;
private ExpandOption option;
private LevelsExpandOption levelOption;
private FilterOption filterOption;
private CountOption countOption;
private OrderByOption orderByOption;
private SearchOption searchOption;
private SelectOption selectOption;
private SkipOption skipOption;
private TopOption topOption;
private List<ExpandItem> itemList;
private ExpandOption expandOption;
@BeforeEach
void setup() throws ODataApplicationException {
sd = mock(JPAServiceDocument.class);
option = mock(ExpandOption.class);
levelOption = mock(LevelsExpandOption.class);
filterOption = mock(FilterOption.class);
countOption = mock(CountOption.class);
orderByOption = mock(OrderByOption.class);
searchOption = mock(SearchOption.class);
selectOption = mock(SelectOption.class);
skipOption = mock(SkipOption.class);
topOption = mock(TopOption.class);
expandOption = mock(ExpandOption.class);
itemList = new ArrayList<>();
expandItem = buildItem(null);
itemList.add(expandItem);
cut = new JPAExpandLevelWrapper(sd, option, expandItem);
}
private ExpandItem buildItem(final UriInfoResource infoResource) {
final ExpandItem item = mock(ExpandItem.class);
when(option.getExpandItems()).thenReturn(itemList);
when(item.getLevelsOption()).thenReturn(levelOption);
when(item.getResourcePath()).thenReturn(infoResource);
when(item.getFilterOption()).thenReturn(filterOption);
when(item.getCountOption()).thenReturn(countOption);
when(item.getOrderByOption()).thenReturn(orderByOption);
when(item.getSearchOption()).thenReturn(searchOption);
when(item.getSelectOption()).thenReturn(selectOption);
when(item.getSkipOption()).thenReturn(skipOption);
when(item.getTopOption()).thenReturn(topOption);
when(item.getExpandOption()).thenReturn(expandOption);
return item;
}
@Test
void checkConstructor() {
assertNotNull(cut);
}
@TestFactory
Iterable<DynamicTest> checkReturnsNull() {
return Arrays.asList(
dynamicTest("FormatOption returns null", () -> assertNull(cut.getFormatOption())),
dynamicTest("IdOption returns null", () -> assertNull(cut.getIdOption())),
dynamicTest("ValueForAlias returns null", () -> assertNull(cut.getValueForAlias(null))),
dynamicTest("ApplyOption returns null", () -> assertNull(cut.getApplyOption())),
dynamicTest("SkipTokenOption returns null", () -> assertNull(cut.getSkipTokenOption())),
dynamicTest("DeltaTokenOption returns null", () -> assertNull(cut.getDeltaTokenOption())),
dynamicTest("CustomQueryOptions empty", () -> assertEquals(0, cut.getCustomQueryOptions().size())),
dynamicTest("ExpandOption returns null if level is < 2", () -> {
when(levelOption.getValue()).thenReturn(1);
assertNull(cut.getExpandOption());
}));
}
@TestFactory
Iterable<DynamicTest> checkReturnsInputProperty() {
return Arrays.asList(
dynamicTest("FilterOption returned", () -> assertEquals(filterOption, cut.getFilterOption())),
dynamicTest("CountOption returned", () -> assertEquals(countOption, cut.getCountOption())),
dynamicTest("OrderByOption returned", () -> assertEquals(orderByOption, cut.getOrderByOption())),
dynamicTest("SearchOption returned", () -> assertEquals(searchOption, cut.getSearchOption())),
dynamicTest("SelectOption returned", () -> assertEquals(selectOption, cut.getSelectOption())),
dynamicTest("SkipOption returned", () -> assertEquals(skipOption, cut.getSkipOption())),
dynamicTest("TopOption returned", () -> assertEquals(topOption, cut.getTopOption())));
}
@Test
void checkLevelOption1() {
when(levelOption.getValue()).thenReturn(1);
assertNull(cut.getExpandOption());
}
@Test
void checkLevelOption2() {
when(levelOption.getValue()).thenReturn(2);
final ExpandOption act = cut.getExpandOption();
assertNotNull(act);
assertEquals(1, act.getExpandItems().size());
}
@Test
void checkExpandOptionProperties() {
when(levelOption.getValue()).thenReturn(2);
when(option.getKind()).thenReturn(SystemQueryOptionKind.APPLY);
when(option.getName()).thenReturn(NAME);
when(option.getText()).thenReturn(TEXT);
final ExpandOption act = cut.getExpandOption();
assertEquals(SystemQueryOptionKind.APPLY, act.getKind());
assertEquals(NAME, act.getName());
assertEquals(TEXT, act.getText());
}
@Test
void checkExpandItemProperties() {
when(levelOption.getValue()).thenReturn(2);
final ExpandOption itemExpandOption = mock(ExpandOption.class);
final ExpandItem itemSecondLevel = mock(ExpandItem.class);
final LevelsExpandOption secondLevelOptions = mock(LevelsExpandOption.class);
final EdmType startTypeFilter = mock(EdmType.class);
when(expandItem.getExpandOption()).thenReturn(itemExpandOption);
when(expandItem.getStartTypeFilter()).thenReturn(startTypeFilter);
when(itemExpandOption.getExpandItems()).thenReturn(Arrays.asList(itemSecondLevel));
when(itemSecondLevel.getLevelsOption()).thenReturn(secondLevelOptions);
when(secondLevelOptions.getValue()).thenReturn(0);
when(secondLevelOptions.isMax()).thenReturn(false);
final ExpandItem act = cut.getExpandOption().getExpandItems().get(0);
assertNull(act.getSearchOption());
assertNull(act.getApplyOption());
assertFalse(act.isRef());
assertFalse(act.hasCountPath());
assertNotNull(act.getExpandOption());
assertEquals(startTypeFilter, act.getStartTypeFilter());
final LevelsExpandOption actLevelOptions = act.getExpandOption().getExpandItems().get(0).getLevelsOption();
assertEquals(1, actLevelOptions.getValue());
assertFalse(actLevelOptions.isMax());
}
@Test
void checkLevelsExpandOptionProperties() {
when(levelOption.getValue()).thenReturn(2);
when(levelOption.isMax()).thenReturn(true);
final LevelsExpandOption act = cut.getExpandOption().getExpandItems().get(0).getLevelsOption();
assertEquals(1, act.getValue());
assertTrue(act.isMax());
}
@Test
void checkExpandOptionContainsInnerExpandOption() {
when(levelOption.getValue()).thenReturn(2);
final ExpandOption act = cut.getExpandOption().getExpandItems().get(0).getExpandOption();
assertNotNull(act.getExpandItems().get(0).getExpandOption());
}
@Test
void checkEntityTypeViaConstructor() {
final JPAEntityType et = mock(JPAEntityType.class);
cut = new JPAExpandLevelWrapper(option, et, null, expandItem);
when(levelOption.getValue()).thenReturn(2);
when(levelOption.isMax()).thenReturn(false);
final LevelsExpandOption act = cut.getExpandOption().getExpandItems().get(0).getLevelsOption();
assertEquals(1, act.getValue());
assertFalse(act.isMax());
assertEquals(et, cut.getEntityType());
}
@Test
void checkTwoLevelItems() {
final UriInfoResource infoResource = mock(UriInfoResource.class);
final UriResource resource = mock(UriResource.class);
final List<UriResource> resourceList = Collections.singletonList(resource);
when(infoResource.getUriResourceParts()).thenReturn(resourceList);
final ExpandItem secondItem = buildItem(infoResource);
itemList.add(secondItem);
final JPAEntityType et = mock(JPAEntityType.class);
when(levelOption.getValue()).thenReturn(2);
when(levelOption.isMax()).thenReturn(false);
cut = new JPAExpandLevelWrapper(option, et, null, secondItem);
final List<ExpandItem> act = cut.getExpandOption().getExpandItems();
assertEquals(1, act.size());
UriInfoResource resourcePath = act.get(0).getResourcePath();
assertEquals(resourceList, resourcePath.getUriResourceParts());
cut = new JPAExpandLevelWrapper(option, et, null, expandItem);
final List<ExpandItem> act2 = cut.getExpandOption().getExpandItems();
assertEquals(1, act2.size());
resourcePath = act2.get(0).getResourcePath();
assertEquals(Collections.emptyList(), resourcePath.getUriResourceParts());
}
@Override
JPAExpandItemPageable getCut() {
return cut;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryODataVersionSupport.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryODataVersionSupport.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQueryODataVersionSupport extends TestBase {
@Test
void testEntityWithMetadataFullVersion400() throws IOException, ODataException {
createHeaders();
addHeader(HttpHeader.ODATA_MAX_VERSION, "4.00");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')?$format=application/json;odata.metadata=full", headers);
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("@odata.context"));
assertNotNull(org.get("@odata.type"));
}
@Test
void testEntityWithMetadataFullVersion401() throws IOException, ODataException {
createHeaders();
addHeader(HttpHeader.ODATA_MAX_VERSION, "4.01");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')?$format=application/json;odata.metadata=full", headers);
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("@context"));
assertNotNull(org.get("@type"));
}
@Test
void testEntityNavigationWithMetadataFullVersion400() throws IOException, ODataException {
createHeaders();
addHeader(HttpHeader.ODATA_MAX_VERSION, "4.00");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/Roles?$format=application/json;odata.metadata=full", headers);
helper.assertStatus(200);
final ObjectNode act = helper.getValue();
assertNotNull(act.get("@odata.context"));
assertNotNull(act.get("value").get(1).get("@odata.type"));
}
@Test
void testEntityNavigationWithMetadataFullVersion401() throws IOException, ODataException {
createHeaders();
addHeader(HttpHeader.ODATA_MAX_VERSION, "4.01");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/Roles?$format=application/json;odata.metadata=full", headers);
helper.assertStatus(200);
final ObjectNode act = helper.getValue();
assertNotNull(act.get("@context"));
assertNotNull(act.get("value").get(1).get("@type"));
}
@Test
void testComplexPropertyWithMetadataFullVersion400() throws IOException, ODataException {
createHeaders();
addHeader(HttpHeader.ODATA_MAX_VERSION, "4.00");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/CommunicationData?$format=application/json;odata.metadata=full", headers);
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("@odata.context"));
assertNotNull(org.get("@odata.type"));
}
@Test
void testComplexPropertyWithMetadataFullVersion401() throws IOException, ODataException {
createHeaders();
addHeader(HttpHeader.ODATA_MAX_VERSION, "4.01");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/CommunicationData?$format=application/json;odata.metadata=full", headers);
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("@context"));
assertNotNull(org.get("@type"));
}
@Test
void testPrimitivePropertyWithMetadataFullVersion400() throws IOException, ODataException {
createHeaders();
addHeader(HttpHeader.ODATA_MAX_VERSION, "4.00");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/LocationName?$format=application/json;odata.metadata=full", headers);
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("@odata.context"));
}
@Test
void testPrimitivePropertyWithMetadataFullVersion401() throws IOException, ODataException {
createHeaders();
addHeader(HttpHeader.ODATA_MAX_VERSION, "4.01");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/LocationName?$format=application/json;odata.metadata=full", headers);
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("@context"));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPACountWatchDogTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPACountWatchDogTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlDynamicExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyValue;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlRecord;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceCount;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.util.AbstractWatchDogTest;
class JPACountWatchDogTest extends AbstractWatchDogTest {
private static final String ES_EXTERNAL_NAME = "Organizations";
private JPACountWatchDog cut;
private static Stream<Arguments> provideIsExpandable() {
return Stream.of(
Arguments.of(Optional.empty(), true),
Arguments.of(createAnnotatable(false, Collections.emptyList()), false),
Arguments.of(createAnnotatable(true, Collections.emptyList()), true),
Arguments.of(createAnnotatable(null, Collections.emptyList()), true));
}
@ParameterizedTest
@MethodSource("provideIsExpandable")
void testIsCountable(final Optional<JPAAnnotatable> annotatable, final boolean exp)
throws ODataJPAProcessException {
cut = new JPACountWatchDog(annotatable);
assertEquals(exp, cut.isCountable());
}
private static Stream<Arguments> provideNonCountableProperties() {
return Stream.of(
Arguments.of(Optional.empty(), Collections.emptyList()),
Arguments.of(createAnnotatable(true, Collections.emptyList(), "Parent"), Arrays.asList("Parent")),
Arguments.of(createAnnotatable(true, Collections.emptyList()), Collections.emptyList()));
}
@ParameterizedTest
@MethodSource("provideNonCountableProperties")
void testNonCountableProperties(final Optional<JPAAnnotatable> annotatable, final List<String> exp)
throws ODataJPAProcessException {
cut = new JPACountWatchDog(annotatable);
assertEquals(exp, cut.getNonCountableProperties());
}
private static Stream<Arguments> provideNonCountableNavigationProperties() {
return Stream.of(
Arguments.of(Optional.empty(), Collections.emptyList()),
Arguments.of(createAnnotatable(true, Arrays.asList("Children")), Arrays.asList("Children")),
Arguments.of(createAnnotatable(true, Collections.emptyList()), Collections.emptyList()));
}
@ParameterizedTest
@MethodSource("provideNonCountableNavigationProperties")
void testNonCountableNavigationProperties(final Optional<JPAAnnotatable> annotatable, final List<String> exp)
throws ODataJPAProcessException {
cut = new JPACountWatchDog(annotatable);
assertEquals(exp, cut.getNonCountableNavigationProperties());
}
@Test
void testWatchChecksCountQueryNotSupported() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(false, Collections.emptyList());
final UriInfoResource uriResource = mock(UriInfoResource.class);
final CountOption countOption = mock(CountOption.class);
when(uriResource.getCountOption()).thenReturn(countOption);
when(countOption.getValue()).thenReturn(Boolean.TRUE);
cut = new JPACountWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(uriResource));
}
@Test
void testWatchChecksCountPathNotSupported() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(false, Collections.emptyList());
final UriInfoResource uriResource = mock(UriInfoResource.class);
final List<UriResource> uriResourceParts = new ArrayList<>();
when(uriResource.getUriResourceParts()).thenReturn(uriResourceParts);
final UriResourceCount count = mock(UriResourceCount.class);
when(count.getKind()).thenReturn(UriResourceKind.count);
final UriResourceEntitySet es = mock(UriResourceEntitySet.class);
uriResourceParts.add(es);
uriResourceParts.add(count);
cut = new JPACountWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(uriResource));
}
private static Stream<Arguments> provideWatchNonCountableProperties() {
return Stream.of(
Arguments.of(Optional.empty(), "Parent", false),
Arguments.of(createAnnotatable(true, Collections.emptyList(), "Parent"), "Parent", true),
Arguments.of(createAnnotatable(true, Collections.emptyList()), "Parent", false));
}
@ParameterizedTest
@MethodSource("provideWatchNonCountableProperties")
void testWatchNonCountableComplexProperties(final Optional<JPAAnnotatable> annotatable,
final String propertyName, final boolean throwException) throws ODataJPAProcessException {
final UriInfoResource uriResource = mock(UriInfoResource.class);
final List<UriResource> uriResourceParts = new ArrayList<>();
when(uriResource.getUriResourceParts()).thenReturn(uriResourceParts);
final UriResourceCount count = mock(UriResourceCount.class);
when(count.getKind()).thenReturn(UriResourceKind.count);
final UriResourceEntitySet es = mock(UriResourceEntitySet.class);
final EdmEntitySet set = mock(EdmEntitySet.class);
when(es.getEntitySet()).thenReturn(set);
when(set.getName()).thenReturn(ES_EXTERNAL_NAME);
final UriResourceComplexProperty collection = mock(UriResourceComplexProperty.class);
final EdmProperty property = mock(EdmProperty.class);
when(collection.getProperty()).thenReturn(property);
when(collection.isCollection()).thenReturn(Boolean.TRUE);
when(property.getName()).thenReturn(propertyName);
when(property.isCollection()).thenReturn(Boolean.TRUE);
uriResourceParts.add(es);
uriResourceParts.add(collection);
uriResourceParts.add(count);
cut = new JPACountWatchDog(annotatable);
if (throwException)
assertThrows(ODataJPAProcessException.class, () -> cut.watch(uriResource));
}
@ParameterizedTest
@MethodSource("provideWatchNonCountableProperties")
void testWatchNonCountableSimpleProperties(final Optional<JPAAnnotatable> annotatable,
final String propertyName, final boolean throwException) throws ODataJPAProcessException {
final UriInfoResource uriResource = mock(UriInfoResource.class);
final List<UriResource> uriResourceParts = new ArrayList<>();
when(uriResource.getUriResourceParts()).thenReturn(uriResourceParts);
final UriResourceCount count = mock(UriResourceCount.class);
when(count.getKind()).thenReturn(UriResourceKind.count);
final UriResourceEntitySet es = mock(UriResourceEntitySet.class);
final EdmEntitySet set = mock(EdmEntitySet.class);
when(es.getEntitySet()).thenReturn(set);
when(set.getName()).thenReturn(ES_EXTERNAL_NAME);
final UriResourcePrimitiveProperty collection = mock(UriResourcePrimitiveProperty.class);
final EdmProperty property = mock(EdmProperty.class);
when(collection.getProperty()).thenReturn(property);
when(collection.isCollection()).thenReturn(Boolean.TRUE);
when(property.getName()).thenReturn(propertyName);
when(property.isCollection()).thenReturn(Boolean.TRUE);
uriResourceParts.add(es);
uriResourceParts.add(collection);
uriResourceParts.add(count);
cut = new JPACountWatchDog(annotatable);
if (throwException)
assertThrows(ODataJPAProcessException.class, () -> cut.watch(uriResource));
}
private static Stream<Arguments> provideWatchNonCountableNavigationProperties() {
return Stream.of(
Arguments.of(Optional.empty(), "Parent", false),
Arguments.of(createAnnotatable(true, Arrays.asList("Parent")), "Parent", true),
Arguments.of(createAnnotatable(true, Collections.emptyList()), "Parent", false));
}
@ParameterizedTest
@MethodSource("provideWatchNonCountableNavigationProperties")
void testWatchNonCountableNavigationProperties(final Optional<JPAAnnotatable> annotatable,
final String propertyName, final boolean throwException) throws ODataJPAProcessException {
final UriInfoResource uriResource = mock(UriInfoResource.class);
final List<UriResource> uriResourceParts = new ArrayList<>();
when(uriResource.getUriResourceParts()).thenReturn(uriResourceParts);
final UriResourceCount count = mock(UriResourceCount.class);
when(count.getKind()).thenReturn(UriResourceKind.count);
final UriResourceEntitySet es = mock(UriResourceEntitySet.class);
final EdmEntitySet set = mock(EdmEntitySet.class);
when(es.getEntitySet()).thenReturn(set);
when(set.getName()).thenReturn(ES_EXTERNAL_NAME);
final UriResourceNavigation navigation = mock(UriResourceNavigation.class);
final EdmNavigationProperty property = mock(EdmNavigationProperty.class);
when(navigation.getProperty()).thenReturn(property);
when(property.getName()).thenReturn(propertyName);
uriResourceParts.add(es);
uriResourceParts.add(navigation);
uriResourceParts.add(count);
cut = new JPACountWatchDog(annotatable);
if (throwException)
assertThrows(ODataJPAProcessException.class, () -> cut.watch(uriResource));
}
private static Optional<JPAAnnotatable> createAnnotatable(final Boolean isCountable,
final List<String> nonCountableNavigation,
final String... nonCountable) {
final JPAAnnotatable annotatable = mock(JPAAnnotatable.class);
final CsdlAnnotation annotation = mock(CsdlAnnotation.class);
final CsdlDynamicExpression expression = mock(CsdlDynamicExpression.class);
final CsdlRecord record = mock(CsdlRecord.class);
final CsdlPropertyValue countableValue = createConstantsExpression(JPACountWatchDog.COUNTABLE,
isCountable == null ? null : isCountable.toString());
final CsdlPropertyValue nonCountableNavigationValue = createCollectionExpression(
JPACountWatchDog.NON_COUNTABLE_NAVIGATION_PROPERTIES, asExpression(nonCountableNavigation));
final CsdlPropertyValue nonCountableValue = createCollectionExpression(JPACountWatchDog.NON_COUNTABLE_PROPERTIES,
asExpression(nonCountable));
final List<CsdlPropertyValue> propertyValues = Arrays.asList(countableValue, nonCountableValue,
nonCountableNavigationValue);
when(annotation.getExpression()).thenReturn(expression);
when(expression.asDynamic()).thenReturn(expression);
when(expression.asRecord()).thenReturn(record);
when(record.getPropertyValues()).thenReturn(propertyValues);
when(annotatable.getExternalName()).thenReturn(ES_EXTERNAL_NAME);
try {
when(annotatable.getAnnotation(JPACountWatchDog.VOCABULARY_ALIAS, JPACountWatchDog.TERM))
.thenReturn(annotation);
} catch (final ODataJPAModelException e) {
fail();
}
return Optional.of(annotatable);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import java.io.IOException;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.odata.v4.provider.JavaBasedCapabilitiesAnnotationsProvider;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQueryNavigationCount extends TestBase {
static Stream<Arguments> provideCountQueries() {
return Stream.of(
arguments("EntitySetCount", "Organizations/$count", "10"),
arguments("EntityNavigateCount", "Organizations('3')/Roles/$count", "3"),
arguments("EntitySetCountWithFilterOn", "AdministrativeDivisions/$count?$filter=Parent eq null", "23"),
arguments("EntitySetCountWithFilterOn", "Organizations/$count?$filter=Address/HouseNumber gt '30'", "7"),
arguments("EntitySetCountWithFilterOnDescription", "Persons/$count?$filter=LocationName eq 'Deutschland'",
"2"));
}
@ParameterizedTest
@MethodSource("provideCountQueries")
void testEntitySetCount(final String text, final String queryString, final String numberOfResults)
throws IOException, ODataException {
final var helper = new IntegrationTestHelper(emf, queryString);
assertEquals(200, helper.getStatus());
assertEquals(numberOfResults, helper.getRawResult(), text);
}
static Stream<Arguments> provideCountTrueQueries() {
return Stream.of(
arguments("EntitySetCount", "Organizations?$count = true", 10),
arguments("EntityNavigateCount", "Organizations('3')/Roles?$count = true", 3),
arguments("EntitySetCountWithFilterOn", "AdministrativeDivisions?$count = true&$filter=Parent eq null", 23),
arguments("EntitySetCountWithFilterOnDescription",
"Persons?$count = true&$filter=LocationName eq 'Deutschland'", 2));
}
@ParameterizedTest
@MethodSource("provideCountTrueQueries")
void testEntitySetCountTrue(final String text, final String queryString, final Integer numberOfResults)
throws IOException, ODataException {
final var helper = new IntegrationTestHelper(emf, queryString);
assertEquals(200, helper.getStatus());
final var act = helper.getValue().get("@odata.count");
assertNotNull(act);
assertEquals(numberOfResults, act.asInt());
}
@Test
void testCountNotSupported() throws IOException, ODataException {
final var helper = new IntegrationTestHelper(emf,
"AnnotationsParents(CodePublisher='Eurostat',CodeID='NUTS2',DivisionCode='BE24')/Children/$count",
new JavaBasedCapabilitiesAnnotationsProvider());
assertEquals(400, helper.getStatus());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.converter.JPAExpandResult.ROOT_RESULT_KEY;
import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.data.ComplexValue;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
import com.sap.olingo.jpa.processor.core.util.TupleDouble;
import com.sap.olingo.jpa.processor.core.util.UriHelperDouble;
class TestJPATupleChildConverter extends TestBase {
public static final int NO_POSTAL_ADDRESS_FIELDS = 8;
public static final int NO_ADMIN_INFO_FIELDS = 2;
private JPATupleChildConverter cut;
private List<Tuple> jpaQueryResult;
private UriHelperDouble uriHelper;
private Map<String, String> keyPredicates;
private final HashMap<String, List<Tuple>> queryResult = new HashMap<>(1);
private JPAODataRequestContextAccess requestContext;
private JPAODataRequestContext context;
private JPAODataSessionContextAccess sessionContext;
private OData odata;
@BeforeEach
void setup() throws ODataException {
helper = new TestHelper(emf, PUNIT_NAME);
jpaQueryResult = new ArrayList<>();
queryResult.put(ROOT_RESULT_KEY, jpaQueryResult);
uriHelper = new UriHelperDouble();
keyPredicates = new HashMap<>();
uriHelper.setKeyPredicates(keyPredicates, "ID");
context = mock(JPAODataRequestContext.class);
sessionContext = mock(JPAODataSessionContextAccess.class);
odata = mock(OData.class);
requestContext = new JPAODataInternalRequestContext(context, sessionContext, odata);
cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, "Organization"),
requestContext);
}
@Test
void checkConvertsEmptyResult() throws ODataApplicationException, ODataJPAModelException {
assertNotNull(cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("Organizations"),
emptyList(), empty()), emptyList()));
}
@Test
void checkConvertsOneResultOneElement() throws ODataApplicationException, ODataJPAModelException {
final HashMap<String, Object> result = new HashMap<>();
result.put("ID", new String("1"));
jpaQueryResult.add(new TupleDouble(result));
keyPredicates.put("1", "Organizations('1')");
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(
"Organizations"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString());
}
@Test
void checkConvertsOneResultOneKey() throws ODataApplicationException, ODataJPAModelException {
final HashMap<String, Object> result = new HashMap<>();
keyPredicates.put("1", "'1'");
result.put("ID", new String("1"));
jpaQueryResult.add(new TupleDouble(result));
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(
"Organizations"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals("Organizations" + "('1')", act.getEntities().get(0).getId().getPath());
}
@Test
void checkConvertsTwoResultsOneElement() throws ODataApplicationException, ODataJPAModelException {
HashMap<String, Object> result;
result = new HashMap<>();
result.put("ID", new String("1"));
jpaQueryResult.add(new TupleDouble(result));
result = new HashMap<>();
result.put("ID", new String("5"));
jpaQueryResult.add(new TupleDouble(result));
keyPredicates.put("1", "Organizations('1')");
keyPredicates.put("5", "Organizations('5')");
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(
"Organizations"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(2, act.getEntities().size());
assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString());
assertEquals("5", act.getEntities().get(1).getProperty("ID").getValue().toString());
}
@Test
void checkConvertsOneResultsTwoElements() throws ODataApplicationException, ODataJPAModelException {
HashMap<String, Object> result;
result = new HashMap<>();
result.put("ID", new String("1"));
result.put("Name1", new String("Willi"));
jpaQueryResult.add(new TupleDouble(result));
keyPredicates.put("1", "Organizations('1')");
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(
"Organizations"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString());
assertEquals("Willi", act.getEntities().get(0).getProperty("Name1").getValue().toString());
}
@Test
void checkConvertsOneResultsTwoElementsSelectionWithEtag() throws ODataApplicationException,
ODataJPAModelException {
cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder,
"BusinessPartnerProtected"), requestContext);
HashMap<String, Object> result;
result = new HashMap<>();
result.put("ID", new String("1"));
result.put("ETag", Integer.valueOf(2));
jpaQueryResult.add(new TupleDouble(result));
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(
"BusinessPartnerProtecteds"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals(1, act.getEntities().get(0).getProperties().size());
assertEquals("1", act.getEntities().get(0).getProperties().get(0).getValue());
assertEquals("ID", act.getEntities().get(0).getProperties().get(0).getName());
assertEquals("\"2\"", act.getEntities().get(0).getETag());
}
@Test
void checkConvertsOneResultsOneComplexElement() throws ODataApplicationException, ODataJPAModelException {
HashMap<String, Object> result;
result = new HashMap<>();
result.put("ID", "1");
result.put("Address/CityName", "Test City");
result.put("Address/Country", "GB");
result.put("Address/PostalCode", "ZE1 3AA");
result.put("Address/StreetName", "Test Road");
result.put("Address/HouseNumber", "123");
result.put("Address/POBox", "155");
result.put("Address/Region", "GB-12");
result.put("Address/CountryName", "Willi");
jpaQueryResult.add(new TupleDouble(result));
keyPredicates.put("1", "Organizations('1')");
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(
"Organizations"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals(ValueType.COMPLEX, act.getEntities().get(0).getProperty("Address").getValueType());
final ComplexValue value = (ComplexValue) act.getEntities().get(0).getProperty("Address").getValue();
assertEquals(NO_POSTAL_ADDRESS_FIELDS, value.getValue().size());
}
@Test
void checkConvertsOneResultsOneNestedComplexElement() throws ODataApplicationException,
ODataJPAModelException {
HashMap<String, Object> result;
result = new HashMap<>();
result.put("ID", "1");
result.put("AdministrativeInformation/Created/By", "Joe Doe");
result.put("AdministrativeInformation/Created/At", "2016-01-22 12:25:23");
result.put("AdministrativeInformation/Updated/By", "Joe Doe");
result.put("AdministrativeInformation/Updated/At", "2016-01-24 14:29:45");
jpaQueryResult.add(new TupleDouble(result));
keyPredicates.put("1", "Organizations('1')");
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(
"Organizations"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
// Check first level
assertEquals(ValueType.COMPLEX, act.getEntities().get(0).getProperty("AdministrativeInformation").getValueType());
final ComplexValue value = (ComplexValue) act.getEntities().get(0).getProperty("AdministrativeInformation")
.getValue();
assertEquals(NO_ADMIN_INFO_FIELDS, value.getValue().size());
// Check second level
assertEquals(ValueType.COMPLEX, value.getValue().get(0).getValueType());
}
@Test
void checkConvertsOneResultsOneElementOfComplexElement() throws ODataApplicationException,
ODataJPAModelException {
HashMap<String, Object> result;
result = new HashMap<>();
result.put("ID", "1");
result.put("Address/Region", new String("CA"));
jpaQueryResult.add(new TupleDouble(result));
keyPredicates.put("1", "Organizations('1')");
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(
"Organizations"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals("CA", ((ComplexValue) act.getEntities().get(0).getProperty("Address").getValue()).getValue().get(0)
.getValue().toString());
}
@Test
void checkConvertsOneResultPrimitiveIncludingTransient() throws ODataApplicationException,
ODataJPAModelException {
cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, "Person"),
requestContext);
final Map<String, Object> result;
final Set<JPAPath> selection = new HashSet<>();
final JPAEntityType et = helper.getJPAEntityType("Persons");
result = new HashMap<>();
result.put("ID", "1");
result.put("FirstName", new String("Willi"));
result.put("LastName", new String("Wichtig"));
jpaQueryResult.add(new TupleDouble(result));
selection.add(et.getPath("ID"));
selection.add(et.getPath("FullName"));
keyPredicates.put("1", "Persons('99')");
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, et, emptyList(), empty()),
selection).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals(2, act.getEntities().get(0).getProperties().size());
assertEquals("Wichtig, Willi", act.getEntities().get(0).getProperty("FullName").getValue().toString());
}
@Test
void checkConvertsOneResultComplexIncludingTransient() throws ODataApplicationException,
ODataJPAModelException {
final Map<String, Object> result;
final Set<JPAPath> selection = new HashSet<>();
final JPAEntityType et = helper.getJPAEntityType("Organizations");
result = new HashMap<>();
result.put("ID", "1");
result.put("Address/Region", new String("CA"));
result.put("Address/StreetName", new String("Test Road"));
result.put("Address/HouseNumber", new String("1230"));
jpaQueryResult.add(new TupleDouble(result));
selection.add(et.getPath("ID"));
selection.add(et.getPath("Address/Street"));
keyPredicates.put("1", "Organizations('1')");
final var act = cut.getResult(new JPAExpandQueryResult(queryResult, null, et, emptyList(), empty()),
selection).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals(2, act.getEntities().get(0).getProperties().size());
assertEquals("Test Road 1230", ((ComplexValue) act.getEntities().get(0).getProperty("Address").getValue())
.getValue().get(0)
.getValue().toString());
}
@Test
void checkConvertMediaStreamStaticMime() throws ODataJPAModelException, NumberFormatException,
ODataApplicationException {
final HashMap<String, List<Tuple>> result = new HashMap<>(1);
result.put("root", jpaQueryResult);
cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, "PersonImage"),
requestContext);
HashMap<String, Object> entityResult;
final byte[] image = { -119, 10 };
entityResult = new HashMap<>();
entityResult.put("ID", "1");
entityResult.put("Image", image);
jpaQueryResult.add(new TupleDouble(entityResult));
final var act = cut.getResult(new JPAExpandQueryResult(result, null, helper.getJPAEntityType(
"PersonImages"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals("image/png", act.getEntities().get(0).getMediaContentType());
}
@Test
void checkConvertMediaStreamDynamicMime() throws ODataJPAModelException, NumberFormatException,
ODataApplicationException {
final HashMap<String, List<Tuple>> result = new HashMap<>(1);
result.put("root", jpaQueryResult);
cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder,
"OrganizationImage"), requestContext);
HashMap<String, Object> entityResult;
final byte[] image = { -119, 10 };
entityResult = new HashMap<>();
entityResult.put("ID", "9");
entityResult.put("Image", image);
entityResult.put("MimeType", "image/svg+xml");
jpaQueryResult.add(new TupleDouble(entityResult));
final var act = cut.getResult(new JPAExpandQueryResult(result, null, helper.getJPAEntityType(
"OrganizationImages"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals("image/svg+xml", act.getEntities().get(0).getMediaContentType());
assertEquals(2, act.getEntities().get(0).getProperties().size());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.apache.olingo.server.api.uri.UriResource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class JPAExpandItemTest {
private JPAExpandItem cut;
@BeforeEach
void setup() {
cut = new JPAExpandItemImpl();
}
@Test
void testDefaultReturnsNull() {
assertNull(cut.getApplyOption());
assertNull(cut.getCountOption());
assertNull(cut.getDeltaTokenOption());
assertNull(cut.getExpandOption());
assertNull(cut.getFilterOption());
assertNull(cut.getFormatOption());
assertNull(cut.getIdOption());
assertNull(cut.getOrderByOption());
assertNull(cut.getSearchOption());
assertNull(cut.getSkipOption());
assertNull(cut.getSkipTokenOption());
assertNull(cut.getTopOption());
assertNull(cut.getEntityType());
}
@Test
void testDefaultReturnsEmptyList() {
assertTrue(cut.getCustomQueryOptions().isEmpty());
}
@Test
void testDefaultReturnsEmptyOption() {
assertTrue(cut.getSkipTokenProvider().isEmpty());
}
private static class JPAExpandItemImpl implements JPAExpandItem {
@Override
public List<UriResource> getUriResourceParts() {
return List.of();
}
@Override
public String getValueForAlias(final String alias) {
return null;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAFunctionRequestProcessorDbTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAFunctionRequestProcessorDbTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.mockito.ArgumentMatchers.any;
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.util.ArrayList;
import java.util.List;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.data.Annotatable;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmReturnType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.core.edm.primitivetype.EdmBoolean;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunctionType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.processor.JPAFunctionRequestProcessor;
import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer;
class JPAFunctionRequestProcessorDbTest {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
private JPAODataDatabaseProcessor dbProcessor;
private OData odata;
private JPAODataRequestContextAccess requestContext;
private ODataRequest request;
private ODataResponse response;
private JPAFunctionRequestProcessor cut;
private EdmFunction edmFunction;
private UriInfo uriInfo;
private List<UriResource> uriResources;
private UriResourceFunction uriResource;
private JPAServiceDocument sd;
private JPADataBaseFunction function;
private JPAOperationSerializer serializer;
private SerializerResult serializerResult;
private EntityManager em;
private JPAHttpHeaderMap headers;
private JPARequestParameterMap parameters;
@BeforeEach
void setup() throws ODataException {
final JPAEdmProvider provider = mock(JPAEdmProvider.class);
em = mock(EntityManager.class);
request = mock(ODataRequest.class);
response = mock(ODataResponse.class);
uriInfo = mock(UriInfo.class);
odata = mock(OData.class);
serializer = mock(JPAOperationSerializer.class);
serializerResult = mock(SerializerResult.class);
requestContext = mock(JPAODataRequestContextAccess.class);
dbProcessor = mock(JPAODataDatabaseProcessor.class);
sd = mock(JPAServiceDocument.class);
uriResource = mock(UriResourceFunction.class);
function = mock(JPADataBaseFunction.class);
uriResources = new ArrayList<>();
edmFunction = mock(EdmFunction.class);
headers = mock(JPAHttpHeaderMap.class);
parameters = mock(JPARequestParameterMap.class);
when(requestContext.getSerializer()).thenReturn(serializer);
when(serializer.serialize(any(Annotatable.class), any(EdmType.class), any(ODataRequest.class)))
.thenReturn(serializerResult);
when(requestContext.getUriInfo()).thenReturn(uriInfo);
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getHeader()).thenReturn(headers);
when(requestContext.getRequestParameter()).thenReturn(parameters);
when(uriInfo.getUriResourceParts()).thenReturn(uriResources);
when(requestContext.getDatabaseProcessor()).thenReturn(dbProcessor);
when(requestContext.getEdmProvider()).thenReturn(provider);
when(provider.getServiceDocument()).thenReturn(sd);
uriResources.add(uriResource);
when(uriResource.getFunction()).thenReturn(edmFunction);
when(sd.getFunction(edmFunction)).thenReturn(function);
when(function.getFunctionType()).thenReturn(EdmFunctionType.UserDefinedFunction);
cut = new JPAFunctionRequestProcessor(odata, requestContext);
}
@Test
void testCallsFunctionWithBooleanReturnType() throws ODataApplicationException, ODataLibraryException,
ODataJPAModelException {
final EdmReturnType edmReturnType = mock(EdmReturnType.class);
final JPAOperationResultParameter resultParam = mock(JPAOperationResultParameter.class);
when(function.getResultParameter()).thenReturn(resultParam);
when(resultParam.getTypeFQN()).thenReturn(new FullQualifiedName(PUNIT_NAME, "CheckRights"));
when(resultParam.getType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return Boolean.class;
}
});
when(edmFunction.getReturnType()).thenReturn(edmReturnType);
when(edmReturnType.getType()).thenReturn(new EdmBoolean());
cut.retrieveData(request, response, ContentType.JSON);
verify(dbProcessor, times(1)).executeFunctionQuery(uriResources, function, em, headers, parameters);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAJoinQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAJoinQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.processor.JPAEmptyDebugger;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
import com.sap.olingo.jpa.processor.core.util.TestQueryBase;
class JPAJoinQueryTest extends TestQueryBase {
private CriteriaBuilder cb;
private EntityManager em;
private JPAODataRequestContextAccess localContext;
private JPAHttpHeaderMap headerMap;
private JPARequestParameterMap parameterMap;
@Override
@BeforeEach
public void setup() throws ODataException, ODataJPAIllegalAccessException {
em = mock(EntityManager.class);
cb = spy(emf.getCriteriaBuilder());
localContext = mock(JPAODataRequestContextAccess.class);
headerMap = mock(JPAHttpHeaderMap.class);
parameterMap = mock(JPARequestParameterMap.class);
buildUriInfo("BusinessPartners", "BusinessPartner");
helper = new TestHelper(emf, PUNIT_NAME);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
jpaEntityType = helper.getJPAEntityType(BusinessPartner.class);
createHeaders();
when(localContext.getUriInfo()).thenReturn(uriInfo);
when(localContext.getEntityManager()).thenReturn(em);
when(localContext.getEdmProvider()).thenReturn(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages));
when(localContext.getDebugger()).thenReturn(new JPAEmptyDebugger());
when(localContext.getOperationConverter()).thenReturn(new JPADefaultDatabaseProcessor());
when(localContext.getHeader()).thenReturn(headerMap);
when(localContext.getRequestParameter()).thenReturn(parameterMap);
when(em.getCriteriaBuilder()).thenReturn(cb);
cut = new JPAJoinQuery(null, localContext);
}
@Test
void testDerivedTypeRequestedTrueTwoLevels() throws ODataJPAModelException {
final var rootType = mock(JPAStructuredType.class);
final var baseType = mock(JPAStructuredType.class);
final var potentialSubType = mock(JPAStructuredType.class);
when(potentialSubType.getBaseType()).thenReturn(baseType);
when(baseType.getBaseType()).thenReturn(rootType);
assertTrue(cut.derivedTypeRequested(rootType, potentialSubType));
}
@Test
void testDerivedTypeRequestedTrue() throws ODataJPAModelException {
final var baseType = mock(JPAStructuredType.class);
final var potentialSubType = mock(JPAStructuredType.class);
when(potentialSubType.getBaseType()).thenReturn(baseType);
assertTrue(cut.derivedTypeRequested(baseType, potentialSubType));
}
@Test
void testDerivedTypeRequestedFalseNoBaseType() throws ODataJPAModelException {
final var baseType = mock(JPAStructuredType.class);
final var potentialSubType = mock(JPAStructuredType.class);
when(potentialSubType.getBaseType()).thenReturn(null);
assertFalse(cut.derivedTypeRequested(baseType, potentialSubType));
}
@Test
void testDerivedTypeRequestedFalseOtherBaseType() throws ODataJPAModelException {
final var baseType = mock(JPAStructuredType.class);
final var baseType2 = mock(JPAStructuredType.class);
final var potentialSubType = mock(JPAStructuredType.class);
when(potentialSubType.getBaseType()).thenReturn(baseType2);
assertFalse(cut.derivedTypeRequested(baseType, potentialSubType));
}
@Test
void testBuildEntityPathListRethrowsException() throws ODataJPAModelException {
final var jpaEntityType = mock(JPAEntityType.class);
when(jpaEntityType.getPathList()).thenThrow(ODataJPAModelException.class);
assertThrows(ODataApplicationException.class, () -> cut.buildEntityPathList(jpaEntityType));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryFactoryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryFactoryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
class JPAExpandQueryFactoryTest {
private JPAExpandQueryFactory cut;
private JPAODataRequestContextAccess requestContext;
private OData odata;
private JPAExpandItemInfo item;
private EntityManager em;
private JPAEdmProvider edmProvider;
private CriteriaBuilder cb;
private JPAAssociationPath associationPath;
@BeforeEach
void setup() throws ODataJPAProcessorException {
final var navigationInfo = mock(JPANavigationPropertyInfo.class);
requestContext = mock(JPAODataRequestContextAccess.class);
odata = OData.newInstance();
item = mock(JPAExpandItemInfo.class);
em = mock(EntityManager.class);
edmProvider = mock(JPAEdmProvider.class);
cb = mock(CriteriaBuilder.class);
associationPath = mock(JPAAssociationPath.class);
when(requestContext.getGroupsProvider()).thenReturn(Optional.empty());
when(requestContext.getClaimsProvider()).thenReturn(Optional.empty());
when(requestContext.getDatabaseProcessor()).thenReturn(null);
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getEdmProvider()).thenReturn(edmProvider);
when(em.getCriteriaBuilder()).thenReturn(cb);
when(navigationInfo.getAssociationPath()).thenReturn(associationPath);
when(item.getHops()).thenReturn(Arrays.asList(navigationInfo, navigationInfo));
}
@Test
void testExpandSubQueryProvidedForProcessor() throws ODataException {
final var processorCb = mock(ProcessorCriteriaBuilder.class);
when(em.getCriteriaBuilder()).thenReturn(processorCb);
cut = new JPAExpandQueryFactory(odata, requestContext, processorCb);
assertTrue(cut.createQuery(item, Optional.empty()) instanceof JPAExpandSubQuery);
}
@Test
void testExpandJoinQueryProvidedForProcessor() throws ODataException {
cut = new JPAExpandQueryFactory(odata, requestContext, cb);
assertTrue(cut.createQuery(item, Optional.empty()) instanceof JPAExpandJoinQuery);
}
@Test
void testExpandSubCountQueryProvidedForProcessor() throws ODataException {
final var processorCb = mock(ProcessorCriteriaBuilder.class);
when(em.getCriteriaBuilder()).thenReturn(processorCb);
cut = new JPAExpandQueryFactory(odata, requestContext, processorCb);
assertTrue(cut.createCountQuery(item, Optional.empty()) instanceof JPAExpandSubCountQuery);
}
@Test
void testExpandJoinCountQueryProvidedForProcessor() throws ODataException {
cut = new JPAExpandQueryFactory(odata, requestContext, cb);
assertTrue(cut.createCountQuery(item, Optional.empty()) instanceof JPAExpandJoinCountQuery);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryPair.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryPair.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class TestJPAQueryPair {
private JPAQueryPair cut;
private JPAAbstractQuery outer;
private JPAAbstractQuery inner;
@BeforeEach
void setup() {
outer = mock(JPAAbstractQuery.class);
inner = mock(JPAAbstractQuery.class);
cut = new JPAQueryPair(inner, outer);
}
@Test
void testGetOuter() {
assertEquals(outer, cut.outer());
}
@Test
void testGetInner() {
assertEquals(inner, cut.inner());
}
@Test
void testToString() {
assertNotNull(cut.toString());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemPageableTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemPageableTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAODataExpandPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
abstract class JPAExpandItemPageableTest {
protected ExpandItem expandItem;
protected JPAEntityType et;
abstract JPAExpandItemPageable getCut();
JPAExpandItem asExpandItem() {
return (JPAExpandItem) getCut();
}
@Test
void testReturnsTopFromPage() {
final var topOption = mock(TopOption.class);
when(topOption.getValue()).thenReturn(10);
when(expandItem.getTopOption()).thenReturn(topOption);
final var page = new JPAODataExpandPage(asExpandItem(), 0, 5, null);
getCut().setPage(page);
assertEquals(5, asExpandItem().getTopOption().getValue());
}
@Test
void testReturnsTopFromUriInfo() {
final var topOption = mock(TopOption.class);
when(topOption.getValue()).thenReturn(10);
when(expandItem.getTopOption()).thenReturn(topOption);
getCut().setPage(null);
assertEquals(10, asExpandItem().getTopOption().getValue());
}
@Test
void testReturnsSkipFromPage() {
final var skipOption = mock(SkipOption.class);
when(skipOption.getValue()).thenReturn(0);
when(expandItem.getSkipOption()).thenReturn(skipOption);
final var page = new JPAODataExpandPage(asExpandItem(), 10, 5, null);
getCut().setPage(page);
assertEquals(10, asExpandItem().getSkipOption().getValue());
}
@Test
void testReturnsSkipFromUriInfo() {
final var skipOption = mock(SkipOption.class);
when(skipOption.getValue()).thenReturn(0);
when(expandItem.getSkipOption()).thenReturn(skipOption);
getCut().setPage(null);
assertEquals(0, asExpandItem().getSkipOption().getValue());
}
@Test
void testReturnsSkipTokenProviderFromPage() {
final var provider = mock(JPAODataSkipTokenProvider.class);
final var page = new JPAODataExpandPage(asExpandItem(), 10, 5, provider);
getCut().setPage(page);
assertEquals(provider, asExpandItem().getSkipTokenProvider().get());
}
@Test
void testReturnsEmptySkipTokenProviderFromPage() {
final var page = new JPAODataExpandPage(asExpandItem(), 10, 5, null);
getCut().setPage(page);
assertTrue(asExpandItem().getSkipTokenProvider().isEmpty());
}
@Test
void testReturnsEmptySkipTokenProviderNoPage() {
assertTrue(asExpandItem().getSkipTokenProvider().isEmpty());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPACollectionExpandWrapperTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPACollectionExpandWrapperTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.FilterOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
class JPACollectionExpandWrapperTest {
private JPACollectionExpandWrapper cut;
private JPAEntityType jpaEntityType;
private UriInfoResource uriInfo;
private FilterOption filterOptions;
private CountOption countOptions;
private SelectOption selectOptions;
private List<UriResource> parts;
@BeforeEach
void setup() {
jpaEntityType = mock(JPAEntityType.class);
uriInfo = mock(UriInfoResource.class);
filterOptions = mock(FilterOption.class);
countOptions = mock(CountOption.class);
selectOptions = mock(SelectOption.class);
when(uriInfo.getFilterOption()).thenReturn(filterOptions);
when(uriInfo.getCountOption()).thenReturn(countOptions);
when(uriInfo.getSelectOption()).thenReturn(selectOptions);
when(uriInfo.getUriResourceParts()).thenReturn(parts);
cut = new JPACollectionExpandWrapper(jpaEntityType, uriInfo);
}
@Test
void testGetCustomQueryOptionsEmpty() {
assertTrue(cut.getCustomQueryOptions().isEmpty());
}
@Test
void testGetEntityType() {
assertEquals(jpaEntityType, cut.getEntityType());
}
@Test
void testGetCountOption() {
assertEquals(countOptions, cut.getCountOption());
}
@Test
void testGetFilterOptions() {
assertEquals(filterOptions, cut.getFilterOption());
}
@Test
void testGetSelectOptions() {
assertEquals(selectOptions, cut.getSelectOption());
}
@Test
void testGetUriResourceParts() {
assertEquals(parts, cut.getUriResourceParts());
}
@Test
void testGetValueForAliasReturnsNull() {
assertNull(cut.getValueForAlias("Test"));
}
@Test
void testGetSkipTokenProvider() {
assertEquals(Optional.empty(), cut.getSkipTokenProvider());
}
@TestFactory
Stream<DynamicTest> testMethodsReturningNull() {
return Stream.of("getExpandOption", "getFormatOption", "getDeltaTokenOption", "getOrderByOption", "getSearchOption",
"getSkipOption", "getSkipTokenOption", "getTopOption", "getApplyOption", "getIdOption")
.map(method -> dynamicTest(method, () -> assertNull(executeMethod(method))));
}
private Object executeMethod(final String methodName) {
final Class<?> clazz = cut.getClass();
try {
final Method method = clazz.getMethod(methodName);
return method.invoke(cut);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
fail();
}
return "Test";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.converter.JPAExpandResult.ROOT_RESULT_KEY;
import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey;
import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
import com.sap.olingo.jpa.processor.core.util.TupleDouble;
import com.sap.olingo.jpa.processor.core.util.UriHelperDouble;
class TestJPATupleChildConverterCompoundKey extends TestBase {
public static final int NO_POSTAL_ADDRESS_FIELDS = 8;
public static final int NO_ADMIN_INFO_FIELDS = 2;
private JPATupleChildConverter cut;
private List<Tuple> jpaQueryResult;
private UriHelperDouble uriHelper;
private Map<String, String> keyPredicates;
private JPAODataRequestContextAccess requestContext;
private JPAODataRequestContext context;
private JPAODataSessionContextAccess sessionContext;
private OData odata;
@BeforeEach
void setup() throws ODataException {
helper = new TestHelper(emf, PUNIT_NAME);
jpaQueryResult = new ArrayList<>();
uriHelper = new UriHelperDouble();
keyPredicates = new HashMap<>();
context = mock(JPAODataRequestContext.class);
sessionContext = mock(JPAODataSessionContextAccess.class);
odata = mock(OData.class);
requestContext = new JPAODataInternalRequestContext(context, sessionContext, odata);
}
@Test
void checkConvertsOneResultsTwoKeys() throws ODataApplicationException, ODataJPAModelException {
// .../BusinessPartnerRoles(BusinessPartnerID='3',RoleCategory='C')
final HashMap<String, List<Tuple>> resultContainer = new HashMap<>(1);
resultContainer.put("root", jpaQueryResult);
cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder,
"BusinessPartnerRole"), requestContext);
HashMap<String, Object> result;
result = new HashMap<>();
result.put("BusinessPartnerID", new String("3"));
result.put("RoleCategory", new String("C"));
jpaQueryResult.add(new TupleDouble(result));
uriHelper.setKeyPredicates(keyPredicates, "BusinessPartnerID");
keyPredicates.put("3", "BusinessPartnerID='3',RoleCategory='C'");
final var act = cut.getResult(new JPAExpandQueryResult(resultContainer, null, helper.getJPAEntityType(
"BusinessPartnerRoles"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals("3", act.getEntities().get(0).getProperty("BusinessPartnerID").getValue().toString());
assertEquals("C", act.getEntities().get(0).getProperty("RoleCategory").getValue().toString());
assertEquals("BusinessPartnerRoles(BusinessPartnerID='3',RoleCategory='C')",
act.getEntities().get(0).getId().getPath());
}
@Test // EmbeddedIds are resolved to elementary key properties
void checkConvertsOneResultsEmbeddedKey() throws ODataApplicationException, ODataJPAModelException {
// .../AdministrativeDivisionDescriptions(CodePublisher='ISO', CodeID='3166-1', DivisionCode='DEU',Language='en')
final HashMap<String, List<Tuple>> resultContainer = new HashMap<>(1);
resultContainer.put("root", jpaQueryResult);
cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder,
"AdministrativeDivisionDescription"), requestContext);
final AdministrativeDivisionDescriptionKey country = new AdministrativeDivisionDescriptionKey();
country.setLanguage("en");
HashMap<String, Object> result;
result = new HashMap<>();
result.put("CodePublisher", new String("ISO"));
result.put("CodeID", new String("3166-1"));
result.put("DivisionCode", new String("DEU"));
result.put("Language", new String("en"));
jpaQueryResult.add(new TupleDouble(result));
uriHelper.setKeyPredicates(keyPredicates, "DivisionCode");
keyPredicates.put("DEU", "CodePublisher='ISO',CodeID='3166-1',DivisionCode='DEU',Language='en'");
final var act = cut.getResult(new JPAExpandQueryResult(resultContainer, null, helper.getJPAEntityType(
"AdministrativeDivisionDescriptions"), emptyList(), empty()), emptyList()).get(ROOT_RESULT_KEY);
assertEquals(1, act.getEntities().size());
assertEquals("ISO", act.getEntities().get(0).getProperty("CodePublisher").getValue().toString());
assertEquals("en", act.getEntities().get(0).getProperty("Language").getValue().toString());
assertEquals(
"AdministrativeDivisionDescriptions(CodePublisher='ISO',CodeID='3166-1',DivisionCode='DEU',Language='en')",
act.getEntities().get(0).getId().getPath());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAOrderByBuilderWatchDogTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAOrderByBuilderWatchDogTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Order;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlCollection;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlDynamicExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyPath;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyValue;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlRecord;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
class JPAOrderByBuilderWatchDogTest {
private JPAOrderByBuilderWatchDog cut;
private JPAAnnotatable annotatable;
private List<CsdlExpression> ascendingOnly;
private List<CsdlExpression> descendingOnly;
private List<CsdlExpression> nonSortable;
private CsdlConstantExpression sortable;
private CsdlAnnotation annotation;
@BeforeEach
void setup() throws ODataJPAQueryException {
annotatable = mock(JPAAnnotatable.class);
annotation = mock(CsdlAnnotation.class);
cut = new JPAOrderByBuilderWatchDog(annotatable);
}
@Test
void testCanCreateInstanceWithoutAnnotatable() {
assertNotNull(new JPAOrderByBuilderWatchDog());
}
private static Stream<Arguments> provideSortingIsNotSupported() {
return Stream.of(
Arguments.of(false, false),
Arguments.of(true, true));
}
@ParameterizedTest
@MethodSource("provideSortingIsNotSupported")
void testHandleIfSortingIsNotSupportedByOrderByGiven(final boolean isAnnotated, final boolean throwsException)
throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
final List<Order> orderClauses = Collections.singletonList(createOrderByClause("AlternativeCode"));
when(sortable.getValue()).thenReturn("false");
cut = new JPAOrderByBuilderWatchDog(annotatable);
assertShallThrow(throwsException, orderClauses);
}
private static Stream<Arguments> provideSortingIsSupported() {
return Stream.of(
Arguments.of(false, false),
Arguments.of(true, false));
}
@ParameterizedTest
@MethodSource("provideSortingIsSupported")
void testHandleIfSortingIsSupportedByOrderByGiven(final boolean isAnnotated, final boolean throwsException)
throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
final List<Order> orderClauses = Collections.singletonList(createOrderByClause("AlternativeCode"));
when(sortable.getValue()).thenReturn("true");
cut = new JPAOrderByBuilderWatchDog(annotatable);
assertShallThrow(throwsException, orderClauses);
}
private static Stream<Arguments> provideHandleSortingOnNonSortableColumn() {
return Stream.of(
Arguments.of(false, false),
Arguments.of(true, true));
}
@ParameterizedTest
@MethodSource("provideHandleSortingOnNonSortableColumn")
void testHandleSortingOnNonSortableColumn(final boolean isAnnotated, final boolean throwsException)
throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
when(sortable.getValue()).thenReturn("true");
final List<Order> orderClauses = Collections.singletonList(createOrderByClause("AlternativeCode"));
nonSortable.add(createAnnotationPath("AlternativeCode"));
cut = new JPAOrderByBuilderWatchDog(annotatable);
assertShallThrow(throwsException, orderClauses);
}
private static Stream<Arguments> provideHandleSortingOnSortableColumn() {
return Stream.of(
Arguments.of(false, false),
Arguments.of(true, false));
}
@ParameterizedTest
@MethodSource("provideHandleSortingOnSortableColumn")
void testHandleSortingOnSortableColumn(final boolean isAnnotated, final boolean throwsException)
throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
when(sortable.getValue()).thenReturn("true");
final List<Order> orderClauses = Collections.singletonList(createOrderByClause("Code"));
nonSortable.add(createAnnotationPath("AlternativeCode"));
cut = new JPAOrderByBuilderWatchDog(annotatable);
assertShallThrow(throwsException, orderClauses);
}
private static Stream<Arguments> provideHandleDescendingOnAscendingOnlyColumn() {
return Stream.of(
Arguments.of(false, false),
Arguments.of(true, true));
}
@ParameterizedTest
@MethodSource("provideHandleDescendingOnAscendingOnlyColumn")
void testHandleDescendingOnAscendingOnlyColumn(final boolean isAnnotated, final boolean throwsException)
throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
when(sortable.getValue()).thenReturn("true");
final List<Order> orderClauses = Collections.singletonList(createOrderByClause("AlternativeCode", false));
ascendingOnly.add(createAnnotationPath("AlternativeCode"));
cut = new JPAOrderByBuilderWatchDog(annotatable);
assertShallThrow(throwsException, orderClauses);
}
private static Stream<Arguments> provideHandleAscendingOnAscendingOnlyColumn() {
return Stream.of(
Arguments.of(false, false),
Arguments.of(true, false));
}
@ParameterizedTest
@MethodSource("provideHandleAscendingOnAscendingOnlyColumn")
void testHandleAscendingOnAscendingOnlyColumn(final boolean isAnnotated, final boolean throwsException)
throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
when(sortable.getValue()).thenReturn("true");
final List<Order> orderClauses = Collections.singletonList(createOrderByClause("AlternativeCode", true));
ascendingOnly.add(createAnnotationPath("AlternativeCode"));
cut = new JPAOrderByBuilderWatchDog(annotatable);
assertShallThrow(throwsException, orderClauses);
}
private static Stream<Arguments> provideHandleAscendingOnDescendingOnlyColumn() {
return Stream.of(
Arguments.of(false, false),
Arguments.of(true, true));
}
@ParameterizedTest
@MethodSource("provideHandleAscendingOnDescendingOnlyColumn")
void testHandleAscendingOnDescendingOnlyColumn(final boolean isAnnotated, final boolean throwsException)
throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
when(sortable.getValue()).thenReturn("true");
final List<Order> orderClauses = Collections.singletonList(createOrderByClause("AlternativeCode", true));
descendingOnly.add(createAnnotationPath("AlternativeCode"));
cut = new JPAOrderByBuilderWatchDog(annotatable);
assertShallThrow(throwsException, orderClauses);
}
private static Stream<Arguments> provideHandleDescendingOnDescendingOnlyColumn() {
return Stream.of(
Arguments.of(false, false),
Arguments.of(true, false));
}
@ParameterizedTest
@MethodSource("provideHandleDescendingOnDescendingOnlyColumn")
void testHandleDescendingOnDescendingOnlyColumn(final boolean isAnnotated, final boolean throwsException)
throws ODataJPAModelException, ODataJPAQueryException {
setAnnotation(isAnnotated);
when(sortable.getValue()).thenReturn("true");
final List<Order> orderClauses = Collections.singletonList(createOrderByClause("AlternativeCode", false));
descendingOnly.add(createAnnotationPath("AlternativeCode"));
cut = new JPAOrderByBuilderWatchDog(annotatable);
assertShallThrow(throwsException, orderClauses);
}
private void assertShallThrow(final boolean throwsException, final List<Order> orderClauses) {
if (throwsException)
assertThrows(ODataJPAQueryException.class, () -> cut.watch(orderClauses));
else
assertDoesNotThrow(() -> cut.watch(orderClauses));
}
private Order createOrderByClause(final String alias) {
return createOrderByClause(alias, true);
}
private Order createOrderByClause(final String alias, final boolean isAscending) {
final Order orderClause = mock(Order.class);
final Expression<?> orderExpression = mock(Expression.class);
when(orderExpression.getAlias()).thenReturn(alias);
when(orderClause.isAscending()).thenReturn(isAscending);
doReturn(orderExpression).when(orderClause).getExpression();
return orderClause;
}
private CsdlPropertyPath createAnnotationPath(final String pathString) {
final CsdlPropertyPath path = mock(CsdlPropertyPath.class);
when(path.asPropertyPath()).thenReturn(path);
when(path.asDynamic()).thenReturn(path);
when(path.getValue()).thenReturn(pathString);
return path;
}
private void setAnnotation(final boolean isAnnotated) throws ODataJPAModelException {
initAnnotation();
if(isAnnotated)
when(annotatable.getAnnotation(JPAOrderByBuilderWatchDog.VOCABULARY_ALIAS, JPAOrderByBuilderWatchDog.TERM))
.thenReturn(annotation);
else
when(annotatable.getAnnotation(JPAOrderByBuilderWatchDog.VOCABULARY_ALIAS, JPAOrderByBuilderWatchDog.TERM))
.thenReturn(null);
}
private void initAnnotation() {
final CsdlDynamicExpression expression = mock(CsdlDynamicExpression.class);
final CsdlRecord record = mock(CsdlRecord.class);
sortable = mock(CsdlConstantExpression.class);
ascendingOnly = new ArrayList<>();
descendingOnly = new ArrayList<>();
nonSortable = new ArrayList<>();
final CsdlPropertyValue sortableValue = mock(CsdlPropertyValue.class);
when(sortableValue.getProperty()).thenReturn(JPAOrderByBuilderWatchDog.SORTABLE);
when(sortableValue.getValue()).thenReturn(sortable);
when(sortable.asConstant()).thenReturn(sortable);
final CsdlPropertyValue ascendingOnlyValue = createCollectionExpression(ascendingOnly,
JPAOrderByBuilderWatchDog.ASCENDING_ONLY_PROPERTIES);
final CsdlPropertyValue descendingOnlyValue = createCollectionExpression(descendingOnly,
JPAOrderByBuilderWatchDog.DESCENDING_ONLY_PROPERTIES);
final CsdlPropertyValue nonSortableValue = createCollectionExpression(nonSortable,
JPAOrderByBuilderWatchDog.NON_SORTABLE_PROPERTIES);
final List<CsdlPropertyValue> propertyValues = Arrays.asList(sortableValue, ascendingOnlyValue, descendingOnlyValue,
nonSortableValue);
when(annotation.getExpression()).thenReturn(expression);
when(expression.asDynamic()).thenReturn(expression);
when(expression.asRecord()).thenReturn(record);
when(record.getPropertyValues()).thenReturn(propertyValues);
}
private CsdlPropertyValue createCollectionExpression(final List<CsdlExpression> collection, final String property) {
final CsdlPropertyValue value = mock(CsdlPropertyValue.class);
final CsdlCollection ascendingOnlyCollection = mock(CsdlCollection.class);
when(value.getProperty()).thenReturn(property);
when(value.getValue()).thenReturn(ascendingOnlyCollection);
when(ascendingOnlyCollection.getItems()).thenReturn(collection);
when(ascendingOnlyCollection.asDynamic()).thenReturn(ascendingOnlyCollection);
when(ascendingOnlyCollection.asCollection()).thenReturn(ascendingOnlyCollection);
return value;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.testmodel.ImageLoader;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQuerySelectByPath extends TestBase {
@Test
void testNavigationToOwnPrimitiveProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/Name1");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("Third Org.", org.get("value").asText());
}
@Test
void testNavigationToOwnEmptyPrimitiveProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('98')/BirthDay");
helper.assertStatus(204);
}
@Test
void testNavigationToOwnPrimitivePropertyEntityDoesNotExistEntity() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('9999')/BirthDay");
helper.assertStatus(404);
}
@Test
void testNavigationToOwnPrimitiveDescriptionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/LocationName");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("Vereinigte Staaten von Amerika", org.get("value").asText());
}
@Test
void testNavigationToComplexProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('4')/Address");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("USA", org.get("Country").asText());
}
@Test
void testNavigationToNotExistingComplexProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('97')/CommunicationData");
helper.assertStatus(204);
}
@Test
void testNavigationToNestedComplexProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('4')/AdministrativeInformation/Created");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("98", org.get("By").asText());
}
@Test
void testNavigationViaComplexAndNaviPropertyToPrimitive() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/AdministrativeInformation/Created/User/FirstName");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("Max", org.get("value").asText());
}
@Test
void testNavigationToComplexPropertySelect() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('4')/Address?$select=Country,Region");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals(3, org.size()); // Node "@odata.context" is also counted
assertEquals("USA", org.get("Country").asText());
assertEquals("US-UT", org.get("Region").asText());
}
@Test
void testNavigationToComplexPrimitiveProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/Address/Region");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("US-CA", org.get("value").asText());
assertTrue(org.get("@odata.context").asText().endsWith("$metadata#Organizations/Address/Region"));
}
@Test
void testNavigationToCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/Comment");
helper.assertStatus(200);
}
@Test
void testNavigationToCollectionWithoutEntries() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('4')/Comment");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
final ArrayNode act = (ArrayNode) org.get("value");
assertNotNull(act);
assertEquals(0, act.size());
}
@Test
void testNavigationToSimplePrimitiveGroupedPropertyNoGroups() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "BusinessPartnerWithGroupss('1')/Country");
helper.assertStatus(204);
}
@Test
void testNavigationToSimpleComplexGroupedPropertyNoGroups() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerWithGroupss('1')/CommunicationData");
helper.assertStatus(204);
}
@Test
void testNavigationToCollectionComplexGroupedPropertyNoGroups() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerWithGroupss('99')/InhouseAddress");
helper.assertStatus(200);
final ArrayNode act = (ArrayNode) helper.getValue().get("value");
assertEquals(2, act.size());
final ObjectNode addr = (ObjectNode) act.get(0);
assertFalse(addr.get("TaskID").isNull());
assertTrue(addr.get("RoomNumber").isNull());
}
@Test
void testNavigationToCollcetionGroupedPropertyNoGroups() throws IOException, ODataException {
IntegrationTestHelper helper = new IntegrationTestHelper(emf, "BusinessPartnerWithGroupss('1')/Comment");
helper.assertStatus(200);
// Ensure empty result works correct
helper = new IntegrationTestHelper(emf, "BusinessPartnerWithGroupss('1')/Comment");
helper.assertStatus(200);
}
@Test
void testNoNavigationButGroupsWithoutGroup() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "BusinessPartnerWithGroupss('99')");
helper.assertStatus(200);
final ObjectNode act = helper.getValue();
assertPresentNotNull(act, "ETag");
assertPresentButNull(act, "CreationDateTime");
assertPresentButNull(act, "Country");
assertPresentButAllNull(act, "CommunicationData");
assertPresentNotEmpty(act, "InhouseAddress", "RoomNumber");
assertPresentButNull(act, "Comment");
}
@Test
void testNoNavigationButGroupsWithOneGroup() throws IOException, ODataException {
final JPAODataGroupsProvider groups = new JPAODataGroupsProvider();
groups.addGroup("Person");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "BusinessPartnerWithGroupss('99')", groups);
helper.assertStatus(200);
final ObjectNode act = helper.getValue();
assertPresentNotNull(act, "ETag");
assertPresentButNull(act, "CreationDateTime");
assertPresentNotNull(act, "Country");
assertPresentNotNull(act, "CommunicationData");
assertPresentNotEmpty(act, "InhouseAddress", "RoomNumber");
assertPresentButNull(act, "Comment");
}
@Test
void testNavigationToStreamValue() throws IOException, ODataException {
new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "PersonImages('99')/$value");
helper.assertStatus(200);
final byte[] act = helper.getBinaryResult();
assertEquals(93316, act.length, 0);
}
@Test
void testNavigationToStreamValueVia() throws IOException, ODataException {
new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('99')/Image/$value");
helper.assertStatus(200);
final byte[] act = helper.getBinaryResult();
assertEquals(93316, act.length, 0);
}
@Test
void testNavigationToComplexAttributeValue() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('4')/AdministrativeInformation/Created/By/$value");
helper.assertStatus(200);
final String act = helper.getRawResult();
assertEquals("98", act);
}
@Test
void testNavigationToPrimitiveAttributeValue() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('4')/ID/$value");
helper.assertStatus(200);
final String act = helper.getRawResult();
assertEquals("4", act);
}
@Test
void testNavigationToDerivedEntities() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartners/com.sap.olingo.jpa.Person");
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(3, act.size());
}
@Test
void testNavigationToDerivedEntityRestrictDerived() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartners/com.sap.olingo.jpa.Person('98')");
helper.assertStatus(200);
final ObjectNode pers = helper.getValue();
assertEquals("98", pers.get("ID").asText());
}
@Test
void testNavigationToDerivedEntityRestrictBase() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartners('98')/com.sap.olingo.jpa.Person");
helper.assertStatus(200);
final ObjectNode person = helper.getValue();
assertEquals("98", person.get("ID").asText());
}
@Test
void testNavigationToDerivedEntityNotFound() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartners('1')/com.sap.olingo.jpa.Person");
helper.assertStatus(404);
}
private void assertPresentButNull(final ObjectNode act, final String property) {
assertTrue(act.has(property));
final JsonNode target = act.get(property);
if (target instanceof ArrayNode)
assertEquals(0, ((ArrayNode) target).size());
else
assertTrue(target.isNull());
}
private void assertPresentButAllNull(final ObjectNode act, final String property) {
assertTrue(act.has(property));
final JsonNode target = act.get(property);
if (target instanceof ObjectNode) {
target.forEach(n -> assertTrue(n.isNull()));
} else {
assertTrue(target.isNull());
}
}
private void assertPresentNotNull(final ObjectNode act, final String property) {
assertTrue(act.has(property));
final JsonNode target = act.get(property);
if (target instanceof ArrayNode)
assertNotEquals(0, ((ArrayNode) target).size());
else
assertFalse(act.get(property).isNull());
}
private void assertPresentNotEmpty(final ObjectNode act, final String property, final String nullProperty) {
assertTrue(act.has(property));
final JsonNode target = act.get(property);
if (target instanceof ArrayNode) {
assertTrue(((ArrayNode) target).size() > 0);
target.forEach(n -> assertFalse(n.isNull()));
assertTrue(target.get(0).get(nullProperty).isNull());
} else {
fail();
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/EdmBoundCastTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/EdmBoundCastTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.edm.EdmBindingTarget;
import org.apache.olingo.commons.api.edm.EdmEntityContainer;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmException;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmTerm;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class EdmBoundCastTest {
private EdmBoundCast cut;
private EdmEntityType et;
private EdmBindingTarget bindingTarget;
@BeforeEach
void setup() {
et = mock(EdmEntityType.class);
bindingTarget = mock(EdmBindingTarget.class);
}
@Test
void testGetName() {
when(et.getName()).thenReturn("Person");
cut = new EdmBoundCast(et, bindingTarget);
assertEquals("Person", cut.getName());
}
@Test
void testGetRelatedBindingTarget() {
final EdmNavigationProperty navigationProperty = mock(EdmNavigationProperty.class);
when(et.getName()).thenReturn("Person");
when(et.getNavigationProperty("Hello")).thenReturn(navigationProperty);
final EdmEntityType boundEt = mock(EdmEntityType.class);
when(navigationProperty.getType()).thenReturn(boundEt);
when(boundEt.getName()).thenReturn("Test");
cut = new EdmBoundCast(et, bindingTarget);
final EdmBindingTarget act = cut.getRelatedBindingTarget("Hello");
assertEquals("Test", act.getName());
}
@Test
void testGetRelatedBindingTargetExceptionOnUnknownNavigation() {
final EdmNavigationProperty navigationProperty = mock(EdmNavigationProperty.class);
when(et.getName()).thenReturn("Person");
when(et.getNavigationProperty("Hello")).thenReturn(null);
final EdmEntityType boundEt = mock(EdmEntityType.class);
when(navigationProperty.getType()).thenReturn(boundEt);
when(boundEt.getName()).thenReturn("Test");
cut = new EdmBoundCast(et, bindingTarget);
assertThrows(EdmException.class, () -> cut.getRelatedBindingTarget("Hello"));
}
@Test
void testGetRelatedBindingTargetExceptionOnEntityTypeNotFound() {
final EdmNavigationProperty navigationProperty = mock(EdmNavigationProperty.class);
when(et.getName()).thenReturn("Person");
when(et.getNavigationProperty("Hello")).thenReturn(navigationProperty);
when(navigationProperty.getType()).thenReturn(null);
cut = new EdmBoundCast(et, bindingTarget);
assertThrows(EdmException.class, () -> cut.getRelatedBindingTarget("Hello"));
}
@Test
void testGetMappingReturnsNull() {
when(et.getName()).thenReturn("Person");
cut = new EdmBoundCast(et, bindingTarget);
assertNull(cut.getMapping());
}
@Test
void testGetTitleReturnsNull() {
when(et.getName()).thenReturn("Person");
cut = new EdmBoundCast(et, bindingTarget);
assertNull(cut.getTitle());
}
@Test
void testGetEntityTypeWithAnnotations() {
when(et.getName()).thenReturn("Person");
cut = new EdmBoundCast(et, bindingTarget);
assertNull(cut.getEntityTypeWithAnnotations());
}
@Test
void testGetEntityContainer() {
final EdmEntityContainer container = mock(EdmEntityContainer.class);
when(bindingTarget.getEntityContainer()).thenReturn(container);
when(et.getName()).thenReturn("Person");
cut = new EdmBoundCast(et, bindingTarget);
assertNotNull(cut.getEntityContainer());
}
@Test
void testGetEntityContainerFromBoundNavigation() {
final EdmEntityContainer container = mock(EdmEntityContainer.class);
when(bindingTarget.getEntityContainer()).thenReturn(container);
when(et.getName()).thenReturn("Person");
final EdmNavigationProperty navigationProperty = mock(EdmNavigationProperty.class);
when(et.getName()).thenReturn("Person");
when(et.getNavigationProperty("Hello")).thenReturn(navigationProperty);
final EdmEntityType boundEt = mock(EdmEntityType.class);
when(navigationProperty.getType()).thenReturn(boundEt);
when(boundEt.getName()).thenReturn("Test");
cut = (EdmBoundCast) new EdmBoundCast(et, bindingTarget).getRelatedBindingTarget("Hello");
assertNotNull(cut.getEntityContainer());
}
@Test
void testGetEntityType() {
final EdmEntityContainer container = mock(EdmEntityContainer.class);
when(bindingTarget.getEntityContainer()).thenReturn(container);
when(et.getName()).thenReturn("Person");
cut = new EdmBoundCast(et, bindingTarget);
assertEquals(et, cut.getEntityType());
}
@Test
void testGetEntityTypeFromBoundNavigation() {
final EdmEntityContainer container = mock(EdmEntityContainer.class);
when(bindingTarget.getEntityContainer()).thenReturn(container);
when(et.getName()).thenReturn("Person");
final EdmNavigationProperty navigationProperty = mock(EdmNavigationProperty.class);
when(et.getName()).thenReturn("Person");
when(et.getNavigationProperty("Hello")).thenReturn(navigationProperty);
final EdmEntityType boundEt = mock(EdmEntityType.class);
when(navigationProperty.getType()).thenReturn(boundEt);
when(boundEt.getName()).thenReturn("Test");
cut = (EdmBoundCast) new EdmBoundCast(et, bindingTarget).getRelatedBindingTarget("Hello");
assertEquals(boundEt, cut.getEntityType());
}
@Test
void testGetNavigationPropertyBindingsReturnsEmptyList() {
final EdmEntityContainer container = mock(EdmEntityContainer.class);
when(bindingTarget.getEntityContainer()).thenReturn(container);
when(et.getName()).thenReturn("Person");
cut = new EdmBoundCast(et, bindingTarget);
assertTrue(cut.getNavigationPropertyBindings().isEmpty());
}
@Test
void testGetAnnotation() {
final EdmTerm term = mock(EdmTerm.class);
final EdmAnnotation exp = mock(EdmAnnotation.class);
when(et.getName()).thenReturn("Person");
when(et.getAnnotation(term, "test")).thenReturn(exp);
cut = new EdmBoundCast(et, bindingTarget);
assertEquals(exp, cut.getAnnotation(term, "test"));
}
@Test
void testGetAnnotations() {
final List<EdmAnnotation> exp = new ArrayList<>();
when(et.getName()).thenReturn("Person");
when(et.getAnnotations()).thenReturn(exp);
cut = new EdmBoundCast(et, bindingTarget);
assertEquals(exp, cut.getAnnotations());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountForExistsQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountForExistsQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.server.api.ODataApplicationException;
import org.mockito.ArgumentCaptor;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
class JPANavigationCountForExistsQueryTest extends JPANavigationCountQueryTest {
@Override
protected JPANavigationSubQuery createCut() throws ODataApplicationException {
return new JPANavigationCountForExistsQuery(odata, helper.sd, jpaEntityType, em, parent, from, association, Optional
.of(claimsProvider), Collections.emptyList());
}
@SuppressWarnings("unchecked")
@Override
protected Subquery<Comparable<?>> createSubQuery() {
return mock(Subquery.class);
}
@Override
protected void assertAggregateClaims(final Path<Object> roleCategoryPath, final Path<Object> idPath,
final Path<Object> sourceIdPath, final List<Path<Comparable<?>>> paths) {
assertNotNull(cut);
verify(cb).equal(sourceIdPath, idPath);
verify(cb).equal(roleCategoryPath, "A");
}
@SuppressWarnings("unchecked")
@Override
protected void assertMultipleJoinColumns(final Subquery<Comparable<?>> subQuery,
final List<Path<Comparable<?>>> paths) {
final ArgumentCaptor<Expression<Comparable<?>>> selectionCaptor = ArgumentCaptor.forClass(Expression.class);
final ArgumentCaptor<List<Expression<?>>> groupByCaptor = ArgumentCaptor.forClass(List.class);
verify(subQuery).select(selectionCaptor.capture());
verify(subQuery).groupBy(groupByCaptor.capture());
assertEquals("codePublisher", selectionCaptor.getValue().getAlias());
assertContainsPath(groupByCaptor.getValue(), 3, "codePublisher", "parentCodeID", "parentDivisionCode");
}
@Override
@SuppressWarnings("unchecked")
protected void assertOneJoinColumnsWithClaims(final Subquery<Comparable<?>> subQuery, final Predicate equalExpression,
final List<Path<Comparable<?>>> paths) {
final ArgumentCaptor<Expression<Comparable<?>>> selectionCaptor = ArgumentCaptor.forClass(Expression.class);
final ArgumentCaptor<List<Expression<?>>> groupByCaptor = ArgumentCaptor.forClass(List.class);
final ArgumentCaptor<Expression<Boolean>> restrictionCaptor = ArgumentCaptor.forClass(Expression.class);
verify(subQuery).select(selectionCaptor.capture());
verify(subQuery).groupBy(groupByCaptor.capture());
verify(subQuery).where(restrictionCaptor.capture());
assertEquals("businessPartnerID", selectionCaptor.getValue().getAlias());
assertContainsPath(groupByCaptor.getValue(), 1, "businessPartnerID");
assertEquals(equalExpression, restrictionCaptor.getValue());
}
@Override
protected void assertLeftEarlyAccess() throws ODataJPAIllegalAccessException {
assertTrue(cut.getLeftPaths().isEmpty());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryResultTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryResultTest.java | package com.sap.olingo.jpa.processor.core.query;
import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives.UuidSortOrder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
import com.sap.olingo.jpa.processor.core.converter.JPAResultConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
import com.sap.olingo.jpa.processor.core.util.TupleDouble;
class JPAExpandQueryResultTest extends TestBase {
private JPAExpandQueryResult cut;
private UriInfoResource uriInfo;
private TopOption top;
private SkipOption skip;
private ExpandOption expand;
private JPAODataRequestContextAccess requestContext;
private TestHelper helper;
private final HashMap<String, List<Tuple>> queryResult = new HashMap<>(1);
private final List<Tuple> tuples = new ArrayList<>();
private JPAEntityType et;
private List<JPANavigationPropertyInfo> hops;
private JPAODataQueryDirectives directives;
@BeforeEach
void setup() throws ODataException {
helper = new TestHelper(emf, PUNIT_NAME);
final UriResourceEntitySet uriEts = mock(UriResourceEntitySet.class);
final JPANavigationPropertyInfo hop0 = new JPANavigationPropertyInfo(helper.sd, uriEts, null, null);
final JPANavigationPropertyInfo hop1 = new JPANavigationPropertyInfo(helper.sd, uriEts, helper.getJPAEntityType(
"Organizations").getAssociationPath("Roles"), null);
hops = Arrays.asList(hop0, hop1);
et = helper.getJPAEntityType("Organizations");
uriInfo = mock(UriInfoResource.class);
directives = new JPAODataQueryDirectives.JPAODataQueryDirectivesImpl(0, UuidSortOrder.AS_JAVA_UUID);
requestContext = mock(JPAODataRequestContextAccess.class);
top = mock(TopOption.class);
skip = mock(SkipOption.class);
expand = mock(ExpandOption.class);
when(requestContext.getUriInfo()).thenReturn(uriInfo);
when(requestContext.getQueryDirectives()).thenReturn(directives);
queryResult.put("root", tuples);
}
@Test
void checkGetKeyBoundaryEmptyBoundaryNoTopSkipPageEmpty() throws ODataJPAModelException, ODataJPAProcessException {
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("Organizations"),
emptyList(), empty());
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertFalse(act.isPresent());
}
@Test
void checkGetKeyBoundaryEmptyBoundaryExpandWithoutTopSkip() throws ODataJPAModelException,
ODataJPAProcessException {
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("AdministrativeDivisionDescriptions"),
emptyList(), empty());
when(uriInfo.getExpandOption()).thenReturn(expand);
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertFalse(act.isPresent());
}
@Test
void checkGetKeyBoundaryEmptyBoundaryNoExpand() throws ODataJPAModelException, ODataJPAProcessException {
final Map<String, Object> key = new HashMap<>(1);
final TupleDouble tuple = new TupleDouble(key);
tuples.add(tuple);
key.put("ID", Integer.valueOf(10));
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("AdministrativeDivisionDescriptions"),
emptyList(), empty());
when(uriInfo.getTopOption()).thenReturn(top);
when(top.getValue()).thenReturn(2);
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertFalse(act.isPresent());
}
@Test
void checkGetKeyBoundaryEmptyBoundaryNotComparable() throws ODataJPAModelException,
NumberFormatException, ODataApplicationException {
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("AdministrativeDivisionDescriptions"),
emptyList(), empty());
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertFalse(act.isPresent());
}
@Test
void checkGetKeyBoundaryEmptyBoundaryNoResult() throws ODataJPAModelException, ODataJPAProcessException {
queryResult.put("root", emptyList());
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("Organizations"),
emptyList(), empty());
when(uriInfo.getTopOption()).thenReturn(top);
when(uriInfo.getExpandOption()).thenReturn(expand);
when(top.getValue()).thenReturn(2);
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertFalse(act.isPresent());
}
@Test
void checkGetKeyBoundaryOneResultWithTop() throws ODataJPAModelException, ODataJPAProcessException {
final Map<String, Object> key = new HashMap<>(1);
final TupleDouble tuple = new TupleDouble(key);
tuples.add(tuple);
key.put("ID", Integer.valueOf(10));
cut = new JPAExpandQueryResult(queryResult, null, et, emptyList(), empty());
when(uriInfo.getTopOption()).thenReturn(top);
when(uriInfo.getExpandOption()).thenReturn(expand);
when(top.getValue()).thenReturn(2);
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertTrue(act.isPresent());
assertEquals(10, act.get().getKeyBoundary().getMin().get(et.getKey().get(0)));
}
@Test
void checkGetKeyBoundaryOneResultWithSkip() throws ODataJPAModelException, ODataJPAProcessException {
addTuple(12);
cut = new JPAExpandQueryResult(queryResult, null, et, emptyList(), empty());
when(uriInfo.getSkipOption()).thenReturn(skip);
when(uriInfo.getExpandOption()).thenReturn(expand);
when(skip.getValue()).thenReturn(2);
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertTrue(act.isPresent());
assertEquals(12, act.get().getKeyBoundary().getMin().get(et.getKey().get(0)));
}
@Test
void checkGetKeyBoundaryContainsNoHops() throws ODataJPAProcessException {
addTuple(12);
cut = new JPAExpandQueryResult(queryResult, null, et, emptyList(), empty());
when(uriInfo.getSkipOption()).thenReturn(skip);
when(uriInfo.getExpandOption()).thenReturn(expand);
when(skip.getValue()).thenReturn(2);
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertTrue(act.isPresent());
assertEquals(2, act.get().getNoHops());
}
@Test
void checkGetKeyBoundaryTwoResultWithSkip() throws ODataJPAModelException, ODataJPAProcessException {
addTuple(12);
addTuple(15);
cut = new JPAExpandQueryResult(queryResult, null, et, emptyList(), empty());
when(uriInfo.getSkipOption()).thenReturn(skip);
when(uriInfo.getExpandOption()).thenReturn(expand);
when(skip.getValue()).thenReturn(2);
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertTrue(act.isPresent());
assertEquals(12, act.get().getKeyBoundary().getMin().get(et.getKey().get(0)));
assertEquals(15, act.get().getKeyBoundary().getMax().get(et.getKey().get(0)));
}
@Test
void checkGetKeyBoundaryOneCompoundResultWithTop() throws ODataJPAModelException, ODataJPAProcessException {
final Map<String, Object> key = new HashMap<>(1);
final TupleDouble tuple = new TupleDouble(key);
tuples.add(tuple);
key.put("codePublisher", "ISO");
key.put("codeID", "3166-1");
key.put("divisionCode", "BEL");
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("AdministrativeDivisionDescriptions"),
emptyList(), empty());
when(uriInfo.getTopOption()).thenReturn(top);
when(uriInfo.getExpandOption()).thenReturn(expand);
when(top.getValue()).thenReturn(2);
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertTrue(act.isPresent());
assertNotNull(act.get().getKeyBoundary().getMin());
assertNull(act.get().getKeyBoundary().getMax());
}
@Test
void checkGetKeyBoundaryEmptyBoundaryNoTopSkipPageSkip() throws ODataJPAModelException, ODataJPAProcessException {
addTuple(12);
when(uriInfo.getExpandOption()).thenReturn(expand);
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("Organizations"),
emptyList(), empty());
final Optional<JPAKeyBoundary> act = cut.getKeyBoundary(requestContext, hops);
assertFalse(act.isPresent());
}
@Test
void checkConstructor() {
cut = new JPAExpandQueryResult(et, List.of());
assertNotNull(cut);
}
@Test
void checkRemoveResult() throws ODataJPAModelException {
final Map<String, Object> key = new HashMap<>(1);
final TupleDouble tuple = new TupleDouble(key);
tuples.add(tuple);
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("AdministrativeDivisionDescriptions"),
emptyList(), empty());
assertNotNull(cut.removeResult("root"));
assertNull(cut.removeResult("root"));
}
@Test
void checkHasCountFalse() throws ODataJPAModelException {
final Map<String, Object> key = new HashMap<>(1);
final TupleDouble tuple = new TupleDouble(key);
tuples.add(tuple);
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("AdministrativeDivisionDescriptions"),
emptyList(), empty());
assertFalse(cut.hasCount());
}
@Test
void checkHasCountTrue() throws ODataJPAModelException {
final Map<String, Object> key = new HashMap<>(1);
final TupleDouble tuple = new TupleDouble(key);
tuples.add(tuple);
final Map<String, Long> counts = new HashMap<>(1);
cut = new JPAExpandQueryResult(queryResult, counts, helper.getJPAEntityType("AdministrativeDivisionDescriptions"),
emptyList(), empty());
assertTrue(cut.hasCount());
}
@Test
void checkPutChildrenThrowsExceptionOnIdenticalKey() throws ODataJPAModelException, ODataApplicationException {
final Map<String, Object> key = new HashMap<>(1);
final TupleDouble tuple = new TupleDouble(key);
tuples.add(tuple);
et = helper.getJPAEntityType(AdministrativeDivision.class);
final Map<JPAAssociationPath, JPAExpandResult> childResults = Map.of(et.getAssociationPath("Parent"),
new JPAExpandQueryResult(et, List.of()));
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(AdministrativeDivision.class),
emptyList(), empty());
cut.putChildren(childResults);
assertThrows(ODataJPAQueryException.class, () -> cut.putChildren(childResults));
}
@Test
void checkConvert() throws ODataJPAModelException {
final JPAResultConverter converter = mock(JPAResultConverter.class);
cut = new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType(AdministrativeDivision.class),
emptyList(), empty());
assertThrows(IllegalAccessError.class, () -> cut.convert(converter));
}
private void addTuple(final Integer value) {
final Map<String, Object> key = new HashMap<>(1);
final TupleDouble tuple = new TupleDouble(key);
tuples.add(tuple);
key.put("ID", value);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQueryNavigation extends TestBase {
private static Stream<Arguments> provideNavigationNoResults() {
return Stream.of(
Arguments.of("Organizations('3')/Roles", 3, "NavigationOneHop"),
Arguments.of("Persons('97')/SupportedOrganizations", 2, "NavigationJoinTableDefined"),
Arguments.of("Organizations('1')/SupportEngineers", 2, "NavigationJoinTableMappedBy"),
Arguments.of(
"BusinessPartnerRoles(BusinessPartnerID='98',RoleCategory='X')/BusinessPartner/com.sap.olingo.jpa.Person/SupportedOrganizations",
1, "NavigationJoinTableDefinedSecondHop"));
}
@ParameterizedTest
@MethodSource("provideNavigationNoResults")
void testNavigationByNumberOfResults(final String url, final Integer exp, final String message) throws IOException,
ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, url);
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(exp, orgs.size(), message);
}
private static Stream<Arguments> provideNavigation() {
return Stream.of(
Arguments.of("Organizations('3')/AdministrativeInformation/Created", "99", "By", "NavigationToComplexValue"),
Arguments.of("BusinessPartnerRoles(BusinessPartnerID='2',RoleCategory='A')/BusinessPartner", "2", "ID",
"NavigationOneHopReverse"),
Arguments.of("Organizations('3')/AdministrativeInformation/Created/User", "99", "ID",
"NavigationViaComplexType"),
Arguments.of("Organizations('3')/AdministrativeInformation/Created/User/Address/AdministrativeDivision",
"3166-1", "ParentCodeID", "NavigationViaComplexTypeTwoHops"));
}
@ParameterizedTest
@MethodSource("provideNavigation")
void testNavigationToComplexValue(final String url, final String exp, final String propertyName, final String message)
throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, url);
helper.assertStatus(200);
final ObjectNode created = helper.getValue();
assertEquals(exp, created.get(propertyName).asText(), message);
}
private static Stream<Arguments> provideNavigationDerived() {
return Stream.of(
Arguments.of("BusinessPartners/com.sap.olingo.jpa.Person",
null, null, 3, 200, "NavigationToDerivedType"),
Arguments.of("BusinessPartners('99')/com.sap.olingo.jpa.Person",
"Mustermann", "LastName", 1, 200, "NavigationToDerivedTypeWithId1"),
Arguments.of("BusinessPartners/com.sap.olingo.jpa.Person('99')",
"Mustermann", "LastName", 1, 200, "NavigationToDerivedTypeWithId2"),
Arguments.of("BusinessPartners('1')/com.sap.olingo.jpa.Person",
null, null, 0, 404, "NavigationToWrongDerivedTypeWithId1"),
Arguments.of(
"BusinessPartnerRoles(BusinessPartnerID='98',RoleCategory='X')/BusinessPartner/com.sap.olingo.jpa.Person",
"Doe", "LastName", 1, 200, "NavigationWithCast"),
Arguments.of(
// maybe the expected status is wrong, but it is hard to implement an 404
"BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')/BusinessPartner/com.sap.olingo.jpa.Person",
null, null, 0, 204, "NavigationWithCastWrongDerivedType"),
Arguments.of(
"Persons('99')/Accounts/com.sap.olingo.jpa.InheritanceLockedSavingAccount",
"LockedSavingAccount", "Type", 1, 200, "NavigationWithCastInheritanceJoined"));
}
@ParameterizedTest
@MethodSource("provideNavigationDerived")
void testNavigationToDerivedType(final String url, final String exp, final String propertyName, final int noResults,
final int status, final String message) throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, url);
helper.assertStatus(status);
if (noResults == 1) {
final ObjectNode created = helper.getValue();
if (created.get("value") == null)
assertEquals(exp, created.get(propertyName).asText(), message);
else
assertEquals(exp, created.get("value").get(0).get(propertyName).asText(), message);
} else if (noResults > 1) {
final ArrayNode created = helper.getValues();
assertEquals(noResults, created.size());
}
}
@Test
void testNoNavigationOneEntity() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("Third Org.", org.get("Name1").asText());
}
@Test
void testNoNavigationOneEntityCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
final ArrayNode comment = (ArrayNode) org.get("Comment");
assertEquals(2, comment.size());
}
@Test
void testNoNavigationOneEntityNoContent() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1000')");
helper.assertStatus(404);
}
@Test
void testNavigationOneHopAndOrderBy() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/Roles?$orderby=RoleCategory desc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(3, orgs.size());
assertEquals("C", orgs.get(0).get("RoleCategory").asText());
assertEquals("A", orgs.get(2).get("RoleCategory").asText());
}
@Test
void testNavigationViaComplexTypeToComplexType() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/AdministrativeInformation/Created/User/AdministrativeInformation");
helper.assertStatus(200);
final ObjectNode admin = helper.getValue();
final ObjectNode created = (ObjectNode) admin.get("Created");
assertEquals("99", created.get("By").asText());
}
@Test
void testNavigationViaComplexTypeToPrimitive() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/AdministrativeInformation/Created/User/AdministrativeInformation/Created/At");
helper.assertStatus(200);
final ObjectNode admin = helper.getValue();
final TextNode at = (TextNode) admin.get("value");
assertNotNull(at);
}
@Test
void testNavigationSelfToOneOneHops() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE352',CodeID='NUTS3',CodePublisher='Eurostat')/Parent");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("NUTS2", org.get("CodeID").asText());
assertEquals("BE35", org.get("DivisionCode").asText());
}
@Test
void testNavigationSelfToOneTwoHops() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE352',CodeID='NUTS3',CodePublisher='Eurostat')/Parent/Parent");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertEquals("NUTS1", org.get("CodeID").asText());
assertEquals("BE3", org.get("DivisionCode").asText());
}
@Test
void testNavigationSelfToManyOneHops() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$orderby=DivisionCode desc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(5, orgs.size());
assertEquals("NUTS2", orgs.get(0).get("CodeID").asText());
assertEquals("BE25", orgs.get(0).get("DivisionCode").asText());
}
@Test
void testNavigationSelfToManyTwoHops() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')/Children?$orderby=DivisionCode desc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(8, orgs.size());
assertEquals("NUTS3", orgs.get(0).get("CodeID").asText());
assertEquals("BE258", orgs.get(0).get("DivisionCode").asText());
}
@Test
void testNavigationSelfToOneThreeHopsNoResult() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/Address/AdministrativeDivision/Parent/Parent");
helper.assertStatus(204);
}
@Test
void testNavigationSelfToManyOneHopsNoResult() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/Address/AdministrativeDivision/Children");
helper.assertStatus(200);
}
@Test
void testNavigationComplexProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/AdministrativeInformation");
helper.assertStatus(200);
final ObjectNode info = helper.getValue();
assertNotNull(info.get("Created"));
assertNotNull(info.get("Updated"));
}
@Test
void testSingletonNavigationComplexProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "CurrentUser/AdministrativeInformation");
helper.assertStatus(200);
final ObjectNode info = helper.getValue();
assertNotNull(info.get("Created"));
assertNotNull(info.get("Updated"));
}
@Test
void testNavigationPrimitiveCollectionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/Comment");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("value"));
assertFalse(org.get("value").isNull());
final ArrayNode values = (ArrayNode) org.get("value");
assertEquals(2, values.size());
assertTrue(values.get(0).asText().equals("This is just a test") || values.get(0).asText().equals(
"This is another test"));
assertTrue(values.get(1).asText().equals("This is just a test") || values.get(1).asText().equals(
"This is another test"));
}
@Test
void testNavigationComplexCollectionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('99')/InhouseAddress");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("value"));
assertFalse(org.get("value").isNull());
final ArrayNode values = (ArrayNode) org.get("value");
assertEquals(2, values.size());
}
@Test
void testNavigationComplexCollectionPropertyEmptyReult() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('98')/InhouseAddress");
helper.assertStatus(200);
}
@Test
void testNavigationPrimitiveCollectionPropertyTwoHops() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')/Organization/Comment");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("value"));
assertFalse(org.get("value").isNull());
final ArrayNode values = (ArrayNode) org.get("value");
assertEquals(2, values.size());
assertTrue(values.get(0).asText().equals("This is just a test") || values.get(0).asText().equals(
"This is another test"));
assertTrue(values.get(1).asText().equals("This is just a test") || values.get(1).asText().equals(
"This is another test"));
}
@Test
void testNavigationViaEntitySetOnly() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "BestOrganizations");
helper.assertStatus(200);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAJoinCountQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAJoinCountQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.processor.JPAEmptyDebugger;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
import com.sap.olingo.jpa.processor.core.util.TestQueryBase;
class JPAJoinCountQueryTest extends TestQueryBase {
private CriteriaBuilder cb;
@SuppressWarnings("rawtypes")
private CriteriaQuery cq;
private EntityManager em;
private JPAODataRequestContextAccess localContext;
private JPAHttpHeaderMap headerMap;
private JPARequestParameterMap parameterMap;
@SuppressWarnings("unchecked")
@Override
@BeforeEach
public void setup() throws ODataException, ODataJPAIllegalAccessException {
em = mock(EntityManager.class);
cb = spy(emf.getCriteriaBuilder());
cq = mock(CriteriaQuery.class);
localContext = mock(JPAODataRequestContextAccess.class);
headerMap = mock(JPAHttpHeaderMap.class);
parameterMap = mock(JPARequestParameterMap.class);
buildUriInfo("BusinessPartners", "BusinessPartner");
helper = new TestHelper(emf, PUNIT_NAME);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
jpaEntityType = helper.getJPAEntityType(BusinessPartner.class);
createHeaders();
when(localContext.getUriInfo()).thenReturn(uriInfo);
when(localContext.getEntityManager()).thenReturn(em);
when(localContext.getEdmProvider()).thenReturn(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages));
when(localContext.getDebugger()).thenReturn(new JPAEmptyDebugger());
when(localContext.getOperationConverter()).thenReturn(new JPADefaultDatabaseProcessor());
when(localContext.getHeader()).thenReturn(headerMap);
when(localContext.getRequestParameter()).thenReturn(parameterMap);
when(em.getCriteriaBuilder()).thenReturn(cb);
when(cb.createQuery(any())).thenReturn(cq);
when(cb.createTupleQuery()).thenReturn(cq);
cut = new JPAJoinCountQuery(null, localContext);
}
@SuppressWarnings("unchecked")
@Test
void testCountResultsIsLong() throws ODataApplicationException {
final TypedQuery<Tuple> typedQuery = mock(TypedQuery.class);
final Expression<Long> countExpression = mock(Expression.class);
final var result = mock(Tuple.class);
when(cq.multiselect(any(), any())).thenReturn(cq);
doReturn(countExpression).when(cb).countDistinct(any());
doReturn(countExpression).when(cb).count(any());
when(em.createQuery(any(CriteriaQuery.class))).thenReturn(typedQuery);
when(result.get(0)).thenReturn(5L);
when(typedQuery.getSingleResult()).thenReturn(result);
final var act = ((JPAJoinCountQuery) cut).countResults();
assertEquals(5L, act);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestNotImplemented.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestNotImplemented.java | package com.sap.olingo.jpa.processor.core.query;
import java.io.IOException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestNotImplemented extends TestBase {
@Test
void testApplyThrowsException() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$apply=aggregate(Area with sum as TotalArea)");
helper.assertStatus(501);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorSimpleAttribute;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
class TestJPAQueryFromClause extends TestBase {
private JPAAbstractJoinQuery cut;
private JPAEntityType jpaEntityType;
private JPAODataSessionContextAccess sessionContext;
private OData odata;
@BeforeEach
void setup() throws ODataException, ODataJPAIllegalAccessException {
odata = mock(OData.class);
final UriInfo uriInfo = mock(UriInfo.class);
final EdmEntitySet odataEs = mock(EdmEntitySet.class);
final EdmEntityType odataType = mock(EdmEntityType.class);
final List<UriResource> resources = new ArrayList<>();
final UriResourceEntitySet esResource = mock(UriResourceEntitySet.class);
when(uriInfo.getUriResourceParts()).thenReturn(resources);
when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(0));
when(esResource.getEntitySet()).thenReturn(odataEs);
when(esResource.getKind()).thenReturn(UriResourceKind.entitySet);
when(esResource.getType()).thenReturn(odataType);
when(odataEs.getName()).thenReturn("Organizations");
when(odataEs.getEntityType()).thenReturn(odataType);
when(odataType.getNamespace()).thenReturn(PUNIT_NAME);
when(odataType.getName()).thenReturn("Organization");
resources.add(esResource);
helper = new TestHelper(emf, PUNIT_NAME);
jpaEntityType = helper.getJPAEntityType("Organizations");
sessionContext = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages),
emf, dataSource, null, null, null);
createHeaders();
final JPAODataRequestContext externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(emf.createEntityManager());
when(externalContext.getRequestParameter()).thenReturn(mock(JPARequestParameterMap.class));
final JPAODataInternalRequestContext requestContext = new JPAODataInternalRequestContext(externalContext,
sessionContext, odata);
requestContext.setUriInfo(uriInfo);
cut = new JPAJoinQuery(null, requestContext);
}
@Test
void checkFromListContainsRoot() throws ODataApplicationException, JPANoSelectionException {
final Map<String, From<?, ?>> act = cut.createFromClause(Collections.emptyList(), Collections.emptyList(), cut.cq,
null);
assertNotNull(act.get(jpaEntityType.getExternalFQN().getFullQualifiedNameAsString()));
}
@Test
void checkFromListOrderByContainsOne() throws ODataApplicationException,
JPANoSelectionException {
final List<JPAProcessorAttribute> orderBy = new ArrayList<>();
final JPAProcessorAttribute exp = buildRoleAssociationPath(orderBy);
final Map<String, From<?, ?>> act = cut.createFromClause(orderBy, new ArrayList<>(), cut.cq, null);
assertNotNull(act.get(exp.getAlias()));
}
@Test
void checkFromListDescriptionAssociationAllFields() throws ODataApplicationException, ODataJPAModelException,
JPANoSelectionException {
final List<JPAProcessorAttribute> orderBy = new ArrayList<>();
final List<JPAPath> descriptionPathList = new ArrayList<>();
final JPAEntityType entity = helper.getJPAEntityType("Organizations");
descriptionPathList.add(entity.getPath("Address/CountryName"));
final Map<String, From<?, ?>> act = cut.createFromClause(orderBy, descriptionPathList, cut.cq, null);
assertEquals(2, act.size());
assertNotNull(act.get("Address/CountryName"));
}
@Test
void checkFromListDescriptionAssociationAllFields2() throws ODataApplicationException, ODataJPAModelException,
JPANoSelectionException {
final List<JPAProcessorAttribute> orderBy = new ArrayList<>();
final List<JPAPath> descriptionPathList = new ArrayList<>();
final JPAEntityType entity = helper.getJPAEntityType("Organizations");
descriptionPathList.add(entity.getPath("Address/RegionName"));
final Map<String, From<?, ?>> act = cut.createFromClause(orderBy, descriptionPathList, cut.cq, null);
assertEquals(2, act.size());
assertNotNull(act.get("Address/RegionName"));
}
@Test
void checkThrowsIfEliminatedByGroups() throws ODataJPAIllegalAccessException, ODataException {
final JPAODataInternalRequestContext requestContext = buildRequestContextToTestGroups(null);
final List<JPAPath> collectionPathList = new ArrayList<>();
final JPAEntityType entity = helper.getJPAEntityType("BusinessPartnerWithGroupss");
collectionPathList.add(entity.getPath("ID"));
collectionPathList.add(entity.getPath("Comment"));
cut = new JPAJoinQuery(null, requestContext);
assertThrows(JPANoSelectionException.class,
() -> cut.createFromClause(Collections.emptyList(), collectionPathList, cut.cq, cut.lastInfo));
}
@Test
void checkDoesNotThrowsIfGroupProvided() throws ODataJPAIllegalAccessException, ODataException,
JPANoSelectionException {
final JPAODataGroupsProvider groups = new JPAODataGroupsProvider();
final JPAODataInternalRequestContext requestContext = buildRequestContextToTestGroups(groups);
groups.addGroup("Company");
final List<JPAPath> collectionPathList = new ArrayList<>();
final JPAEntityType entity = helper.getJPAEntityType("BusinessPartnerWithGroupss");
collectionPathList.add(entity.getPath("ID"));
collectionPathList.add(entity.getPath("Comment"));
cut = new JPAJoinQuery(null, requestContext);
final Map<String, From<?, ?>> act = cut.createFromClause(Collections.emptyList(), collectionPathList, cut.cq,
cut.lastInfo);
assertEquals(2, act.size());
}
private JPAODataInternalRequestContext buildRequestContextToTestGroups(final JPAODataGroupsProvider groups)
throws ODataJPAIllegalAccessException {
final UriInfo uriInfo = mock(UriInfo.class);
final EdmEntitySet odataEs = mock(EdmEntitySet.class);
final EdmEntityType odataType = mock(EdmEntityType.class);
final List<UriResource> resources = new ArrayList<>();
final UriResourceEntitySet esResource = mock(UriResourceEntitySet.class);
final UriResourcePrimitiveProperty ppResource = mock(UriResourcePrimitiveProperty.class);
final EdmProperty ppProperty = mock(EdmProperty.class);
when(uriInfo.getUriResourceParts()).thenReturn(resources);
when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(0));
when(esResource.getEntitySet()).thenReturn(odataEs);
when(esResource.getKind()).thenReturn(UriResourceKind.entitySet);
when(esResource.getType()).thenReturn(odataType);
when(odataEs.getName()).thenReturn("BusinessPartnerWithGroupss");
when(odataEs.getEntityType()).thenReturn(odataType);
when(odataType.getNamespace()).thenReturn(PUNIT_NAME);
when(odataType.getName()).thenReturn("BusinessPartnerWithGroups");
when(ppResource.isCollection()).thenReturn(true);
when(ppResource.getProperty()).thenReturn(ppProperty);
when(ppProperty.getName()).thenReturn("Comment");
resources.add(esResource);
resources.add(ppResource);
final JPAODataRequestContext externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(emf.createEntityManager());
when(externalContext.getGroupsProvider()).thenReturn(Optional.ofNullable(groups));
when(externalContext.getRequestParameter()).thenReturn(mock(JPARequestParameterMap.class));
final JPAODataInternalRequestContext requestContext = new JPAODataInternalRequestContext(externalContext,
sessionContext, odata);
requestContext.setUriInfo(uriInfo);
return requestContext;
}
@SuppressWarnings("unchecked")
private JPAProcessorAttribute buildRoleAssociationPath(final List<JPAProcessorAttribute> orderBy) {
final var attribute = mock(JPAProcessorSimpleAttribute.class);
final var join = mock(Join.class);
when(attribute.requiresJoin()).thenReturn(true);
when(attribute.getAlias()).thenReturn("Roles");
when(attribute.createJoin()).thenReturn(join);
when(attribute.setTarget(any(), any(), any())).thenReturn(attribute);
orderBy.add(attribute);
return attribute;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterExpression;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRoleProtected;
import com.sap.olingo.jpa.processor.core.testmodel.JoinPartnerRoleRelation;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
abstract class JPANavigationCountQueryTest extends TestBase {
protected JPANavigationSubQuery cut;
protected TestHelper helper;
protected EntityManager em;
protected OData odata;
protected UriResourceNavigation uriResourceItem;
protected JPAAbstractQuery parent;
protected JPAAssociationPath association;
protected From<?, ?> from;
protected JPAODataClaimProvider claimsProvider;
protected JPAEntityType jpaEntityType;
@SuppressWarnings("rawtypes")
protected CriteriaQuery cq;
protected CriteriaBuilder cb;
protected Subquery<Comparable<?>> subQuery;
protected JPAODataRequestContextAccess requestContext;
public JPANavigationCountQueryTest() {
super();
}
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() throws ODataException {
helper = getHelper();
em = mock(EntityManager.class);
parent = mock(JPAAbstractQuery.class);
claimsProvider = mock(JPAODataClaimProvider.class);
odata = OData.newInstance();
uriResourceItem = mock(UriResourceNavigation.class);
cq = mock(CriteriaQuery.class);
cb = mock(CriteriaBuilder.class);
subQuery = createSubQuery();
from = mock(From.class);
requestContext = mock(JPAODataRequestContextAccess.class);
final UriParameter key = mock(UriParameter.class);
when(em.getCriteriaBuilder()).thenReturn(cb);
when(uriResourceItem.getKeyPredicates()).thenReturn(Collections.singletonList(key));
when(parent.getQuery()).thenReturn(cq);
when(cq.<Comparable<?>> subquery(any(Class.class))).thenReturn(subQuery);
when(claimsProvider.get("RoleCategory")).thenReturn(Collections.singletonList(new JPAClaimsPair<>("A")));
doReturn(BusinessPartnerProtected.class).when(from).getJavaType();
}
protected void createEdmEntityType(final Class<?> clazz) throws ODataJPAModelException {
jpaEntityType = helper.getJPAEntityType(clazz);
}
protected abstract Subquery<Comparable<?>> createSubQuery();
@Test
void testCutExists() throws ODataApplicationException, ODataJPAModelException {
association = helper.getJPAAssociationPath(BusinessPartnerProtected.class, "RolesProtected");
createEdmEntityType(BusinessPartnerRoleProtected.class);
cut = createCut();
assertNotNull(cut);
}
protected abstract JPANavigationSubQuery createCut() throws ODataApplicationException;
@Test
void testGetSubQueryThrowsExceptionWhenChildQueryProvided() throws ODataApplicationException, ODataJPAModelException {
association = helper.getJPAAssociationPath(BusinessPartnerProtected.class, "RolesProtected");
createEdmEntityType(BusinessPartnerRoleProtected.class);
cut = createCut();
assertThrows(ODataJPAQueryException.class, () -> cut.getSubQuery(subQuery, null, Collections.emptyList()));
}
@SuppressWarnings("unchecked")
@Test
void testQueryWithJoinTableAggregateWithClaim() throws ODataApplicationException, ODataJPAModelException,
EdmPrimitiveTypeException, ODataJPAIllegalAccessException {
association = helper.getJPAAssociationPath(BusinessPartnerProtected.class, "RolesJoinProtected");
createEdmEntityType(BusinessPartnerRoleProtected.class);
final Root<JoinPartnerRoleRelation> queryJoinTable = mock(Root.class);
final Root<BusinessPartnerRoleProtected> queryRoot = mock(Root.class);
final Root<BusinessPartnerProtected> parentRoot = mock(Root.class);
when(subQuery.from(JoinPartnerRoleRelation.class)).thenReturn(queryJoinTable);
when(subQuery.from(BusinessPartnerRoleProtected.class)).thenReturn(queryRoot);
final JPAFilterExpression expression = createCountFilter();
final JPAODataDatabaseOperations converterExtension = mock(JPAODataDatabaseOperations.class);
final Join<Object, Object> innerJoin = mock(Join.class);
final Path<Object> roleCategoryPath = mock(Path.class);
final Path<Object> idPath = mock(Path.class);
final Path<Object> keyPath = mock(Path.class);
final Path<Object> sourceIdPath = mock(Path.class);
final Predicate equalExpression1 = mock(Predicate.class);
when(parent.getContext()).thenReturn(requestContext);
when(parent.getJpaEntity()).thenReturn(helper.getJPAEntityType(BusinessPartnerProtected.class));
when(requestContext.getOperationConverter()).thenReturn(converterExtension);
when(idPath.getAlias()).thenReturn("iD");
when(subQuery.from(BusinessPartnerProtected.class)).thenReturn(parentRoot);
when(parentRoot.join("rolesJoinProtected", JoinType.LEFT)).thenReturn(innerJoin);
when(queryRoot.get("roleCategory")).thenReturn(roleCategoryPath);
when(queryJoinTable.get("key")).thenReturn(keyPath);
when(parentRoot.get("key")).thenReturn(keyPath);
when(from.get("iD")).thenReturn(idPath);
when(keyPath.get("sourceID")).thenReturn(sourceIdPath);
when(cb.equal(keyPath, keyPath)).thenReturn(equalExpression1);
when(innerJoin.get("roleCategory")).thenReturn(roleCategoryPath);
cut = createCut();
cut.buildExpression(expression, Collections.emptyList());
cut.getSubQuery(null, null, Collections.emptyList());
assertAggregateClaims(roleCategoryPath, idPath, sourceIdPath, cut.getLeftPaths());
}
@SuppressWarnings("unchecked")
@Test
void testQueryMultipleJoinColumns() throws ODataApplicationException, ODataJPAModelException,
EdmPrimitiveTypeException, ODataJPAIllegalAccessException {
association = helper.getJPAAssociationPath(AdministrativeDivision.class, "Children");
createEdmEntityType(AdministrativeDivision.class);
final Root<AdministrativeDivision> queryRoot = mock(Root.class);
when(subQuery.from(AdministrativeDivision.class)).thenReturn(queryRoot);
final JPAODataDatabaseOperations converterExtension = mock(JPAODataDatabaseOperations.class);
when(parent.getContext()).thenReturn(requestContext);
when(parent.getJpaEntity()).thenReturn(helper.getJPAEntityType(AdministrativeDivision.class));
when(requestContext.getOperationConverter()).thenReturn(converterExtension);
final JPAFilterExpression expression = createCountFilter();
createAttributePath(queryRoot, "codePublisher", "codeID", "divisionCode", "parentCodeID", "parentDivisionCode");
createAttributePath(from, "codePublisher", "codeID", "divisionCode", "parentCodeID", "parentDivisionCode");
cut = createCut();
cut.buildExpression(expression, Collections.emptyList());
cut.getSubQuery(null, null, Collections.emptyList());
assertNotNull(cut);
assertMultipleJoinColumns(subQuery, cut.getLeftPaths());
}
@SuppressWarnings("unchecked")
@Test
void testQueryOneJoinColumnsWithClaims() throws ODataApplicationException, ODataJPAModelException,
EdmPrimitiveTypeException, ODataJPAIllegalAccessException {
association = helper.getJPAAssociationPath(BusinessPartnerProtected.class, "RolesProtected");
createEdmEntityType(BusinessPartnerRoleProtected.class);
final Path<Object> roleCategoryPath = mock(Path.class);
final Root<BusinessPartnerRoleProtected> queryRoot = mock(Root.class);
when(subQuery.from(BusinessPartnerRoleProtected.class)).thenReturn(queryRoot);
when(queryRoot.get("roleCategory")).thenReturn(roleCategoryPath);
final JPAODataDatabaseOperations converterExtension = mock(JPAODataDatabaseOperations.class);
when(parent.getContext()).thenReturn(requestContext);
when(parent.getJpaEntity()).thenReturn(helper.getJPAEntityType(BusinessPartnerProtected.class));
when(requestContext.getOperationConverter()).thenReturn(converterExtension);
final JPAFilterExpression expression = createCountFilter();
createAttributePath(queryRoot, "businessPartnerID");
final Predicate equalExpression1 = mock(Predicate.class);
when(cb.equal(roleCategoryPath, "A")).thenReturn(equalExpression1);
createAttributePath(from, "iD");
cut = createCut();
cut.buildExpression(expression, Collections.emptyList());
cut.getSubQuery(null, null, Collections.emptyList());
assertNotNull(cut);
assertOneJoinColumnsWithClaims(subQuery, equalExpression1, cut.getLeftPaths());
}
@Test
void testGetLeftOnEarlyAccess() throws ODataApplicationException, ODataJPAIllegalAccessException,
ODataJPAModelException {
association = helper.getJPAAssociationPath(BusinessPartnerProtected.class, "RolesProtected");
createEdmEntityType(BusinessPartnerRoleProtected.class);
cut = createCut();
assertLeftEarlyAccess();
}
protected abstract void assertLeftEarlyAccess() throws ODataJPAIllegalAccessException;
protected abstract void assertOneJoinColumnsWithClaims(final Subquery<Comparable<?>> subQuery,
final Predicate equalExpression, final List<Path<Comparable<?>>> paths);
protected abstract void assertMultipleJoinColumns(final Subquery<Comparable<?>> subQuery,
final List<Path<Comparable<?>>> paths);
protected abstract void assertAggregateClaims(final Path<Object> roleCategoryPath, final Path<Object> idPath,
final Path<Object> sourceIdPath, final List<Path<Comparable<?>>> paths);
protected JPAFilterExpression createCountFilter()
throws EdmPrimitiveTypeException {
final Literal literal = mock(Literal.class);
final EdmPrimitiveType edmType = mock(EdmPrimitiveType.class);
final UriInfoResource uriInfoResource = mock(UriInfoResource.class);
final UriResource uriResource = mock(UriResource.class);
final Member member = mock(Member.class);
final JPAFilterExpression expression = new JPAFilterExpression(member, literal, BinaryOperatorKind.EQ);
when(uriInfoResource.getUriResourceParts()).thenReturn(Collections.singletonList(uriResource));
when(uriResource.getKind()).thenReturn(UriResourceKind.count);
when(member.getResourcePath()).thenReturn(uriInfoResource);
when(literal.getText()).thenReturn("1");
when(literal.getType()).thenReturn(edmType);
when(edmType.valueOfString(any(), any(), any(), any(), any(), any(), any())).thenReturn(Integer.valueOf(1));
return expression;
}
@SuppressWarnings("unchecked")
protected void createAttributePath(final From<?, ?> from, final String... names) {
for (final String name : names) {
final Path<Object> path = mock(jakarta.persistence.criteria.Path.class);
when(from.get(name)).thenReturn(path);
when(path.getAlias()).thenReturn(name);
}
}
protected void assertContainsPath(final List<?> pathList, final int expSize, final String... names) {
final List<String> selections = pathList.stream().map(path -> ((Selection<?>) path).getAlias()).toList();
assertEquals(expSize, pathList.size());
for (final String name : names) {
assertTrue(selections.contains(name));
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPACollectionJoinQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPACollectionJoinQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Tuple;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Root;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
class JPACollectionJoinQueryTest extends TestBase {
private TestHelper helper;
private JPAODataRequestContextAccess requestContext;
private JPAODataClaimProvider claimProvider;
private EntityManager em;
@BeforeEach
void setup() throws ODataException {
helper = new TestHelper(emf, PUNIT_NAME);
requestContext = mock(JPAODataRequestContextAccess.class);
claimProvider = mock(JPAODataClaimProvider.class);
em = emf.createEntityManager();
final JPAServiceDebugger debugger = mock(JPAServiceDebugger.class);
when(requestContext.getDebugger()).thenReturn(debugger);
when(requestContext.getClaimsProvider()).thenReturn(Optional.of(claimProvider));
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getHeader()).thenReturn(mock(JPAHttpHeaderMap.class));
when(requestContext.getRequestParameter()).thenReturn(mock(JPARequestParameterMap.class));
when(requestContext.getEdmProvider()).thenReturn(helper.edmProvider);
when(requestContext.getOperationConverter()).thenReturn(new JPADefaultDatabaseProcessor());
}
@Test
void createQuery() throws ODataException {
final JPACollectionItemInfo item = createBusinessPartnerToComment(null);
assertNotNull(new JPACollectionJoinQuery(OData.newInstance(), item, requestContext, Optional.empty()));
}
@Test
void createWhereThrowsExceptionOnMissingClaim() throws ODataException {
final JPACollectionItemInfo item = createBusinessPartnerToComment(null);
final JPACollectionJoinQuery cut = new JPACollectionJoinQuery(OData.newInstance(), item, requestContext, Optional
.empty());
assertThrows(ODataJPAQueryException.class, () -> cut.createWhere());
}
@Test
void createWhereContainsProtected() throws ODataException {
final CriteriaQuery<Tuple> bp = em.getCriteriaBuilder().createTupleQuery();
final Root<BusinessPartnerProtected> from = bp.from(BusinessPartnerProtected.class);
final JPACollectionItemInfo item = createBusinessPartnerToComment(from);
final JPACollectionJoinQuery cut = new JPACollectionJoinQuery(OData.newInstance(), item, requestContext, Optional
.empty());
final List<JPAClaimsPair<String>> claims = Arrays.asList(new JPAClaimsPair<>("Willi"));
doReturn(claims).when(claimProvider).get("UserId");
assertNotNull(cut.createWhere());
}
private JPACollectionItemInfo createBusinessPartnerToComment(final From<?, ?> from) throws ODataJPAModelException,
ODataApplicationException {
final JPACollectionItemInfo item = mock(JPACollectionItemInfo.class);
final JPAEntityType et = helper.getJPAEntityType(BusinessPartnerProtected.class);
final UriResourceEntitySet uriEts = mock(UriResourceEntitySet.class);
final EdmEntityType edmType = mock(EdmEntityType.class);
final EdmEntitySet edmSet = mock(EdmEntitySet.class);
final List<JPANavigationPropertyInfo> hops = new ArrayList<>();
JPANavigationPropertyInfo hop = new JPANavigationPropertyInfo(helper.sd, uriEts,
et.getCollectionAttribute("Comment").asAssociation(), null);
hop.setFromClause(from);
hops.add(hop);
hop = new JPANavigationPropertyInfo(helper.sd, null, null, et);
hops.add(hop);
final UriInfoResource uriInfo = mock(UriInfoResource.class);
final JPACollectionExpandWrapper wrappedUriInfo = new JPACollectionExpandWrapper(et, uriInfo);
when(item.getEntityType()).thenReturn(et);
when(item.getUriInfo()).thenReturn(wrappedUriInfo);
when(item.getHops()).thenReturn(hops);
when(item.getExpandAssociation()).thenReturn(et.getCollectionAttribute("Comment").asAssociation());
when(uriEts.getType()).thenReturn(edmType);
when(uriEts.getEntitySet()).thenReturn(edmSet);
when(edmSet.getName()).thenReturn(helper.sd.getEntitySet(et).getExternalName());
when(edmType.getNamespace()).thenReturn(PUNIT_NAME);
when(edmType.getName()).thenReturn(et.getExternalName());
return item;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.util.EdmEntityTypeDouble;
import com.sap.olingo.jpa.processor.core.util.ExpandItemDouble;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
import com.sap.olingo.jpa.processor.core.util.TupleDouble;
import com.sap.olingo.jpa.processor.core.util.UriInfoDouble;
class TestJPAExpandQueryCreateResult extends TestBase {
private JPAExpandJoinQuery cut;
private JPAODataSessionContextAccess sessionContext;
private JPAODataInternalRequestContext requestContext;
private OData odata;
@BeforeEach
void setup() throws ODataException, ODataJPAIllegalAccessException {
helper = new TestHelper(emf, PUNIT_NAME);
createHeaders();
final EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "BusinessPartnerRole");
sessionContext = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null,
TestBase.enumPackages), emf, dataSource, null, null, null);
final JPAODataRequestContext externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(emf.createEntityManager());
odata = OData.newInstance();
requestContext = new JPAODataInternalRequestContext(externalContext, sessionContext, odata);
requestContext.setUriInfo(new UriInfoDouble(new ExpandItemDouble(targetEntity).getResourcePath()));
cut = new JPAExpandJoinQuery(null, helper.getJPAAssociationPath("Organizations", "Roles"),
helper.sd.getEntity(targetEntity), requestContext);
}
@Test
void checkConvertOneResult() throws ODataJPAModelException, ODataApplicationException {
final JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles");
final List<Tuple> result = new ArrayList<>();
final HashMap<String, Object> oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "1");
oneResult.put("RoleCategory", "A");
final Tuple tuple = new TupleDouble(oneResult);
result.add(tuple);
final Map<String, List<Tuple>> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE);
assertNotNull(act.get("1"));
assertEquals(1, act.get("1").size());
assertEquals("1", act.get("1").get(0).get("BusinessPartnerID"));
}
@Test
void checkConvertTwoResultOneParent() throws ODataJPAModelException, ODataApplicationException {
final JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles");
final List<Tuple> result = new ArrayList<>();
HashMap<String, Object> oneResult;
Tuple tuple;
oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "2");
oneResult.put("RoleCategory", "A");
tuple = new TupleDouble(oneResult);
result.add(tuple);
oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "2");
oneResult.put("RoleCategory", "C");
tuple = new TupleDouble(oneResult);
result.add(tuple);
final Map<String, List<Tuple>> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE);
assertEquals(1, act.size());
assertNotNull(act.get("2"));
assertEquals(2, act.get("2").size());
assertEquals("2", act.get("2").get(0).get("BusinessPartnerID"));
}
@Test
void checkConvertTwoResultOneParentTop1() throws ODataJPAModelException, ODataApplicationException {
final JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles");
final List<Tuple> result = new ArrayList<>();
HashMap<String, Object> oneResult;
Tuple tuple;
oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "2");
oneResult.put("RoleCategory", "A");
tuple = new TupleDouble(oneResult);
result.add(tuple);
oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "2");
oneResult.put("RoleCategory", "C");
tuple = new TupleDouble(oneResult);
result.add(tuple);
final Map<String, List<Tuple>> act = cut.convertResult(result, exp, 0, 1);
assertEquals(1, act.size());
assertNotNull(act.get("2"));
assertEquals(1, act.get("2").size());
assertEquals("A", act.get("2").get(0).get("RoleCategory"));
}
@Test
void checkConvertTwoResultOneParentSkip1() throws ODataJPAModelException, ODataApplicationException {
final JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles");
final List<Tuple> result = new ArrayList<>();
HashMap<String, Object> oneResult;
Tuple tuple;
oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "2");
oneResult.put("RoleCategory", "A");
tuple = new TupleDouble(oneResult);
result.add(tuple);
oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "2");
oneResult.put("RoleCategory", "C");
tuple = new TupleDouble(oneResult);
result.add(tuple);
final Map<String, List<Tuple>> act = cut.convertResult(result, exp, 1, 1000);
assertEquals(1, act.size());
assertNotNull(act.get("2"));
assertEquals(1, act.get("2").size());
assertEquals("C", act.get("2").get(0).get("RoleCategory"));
}
@Test
void checkConvertTwoResultTwoParent() throws ODataJPAModelException, ODataApplicationException {
final JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles");
final List<Tuple> result = new ArrayList<>();
HashMap<String, Object> oneResult;
Tuple tuple;
oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "1");
oneResult.put("RoleCategory", "A");
tuple = new TupleDouble(oneResult);
result.add(tuple);
oneResult = new HashMap<>();
oneResult.put("BusinessPartnerID", "2");
oneResult.put("RoleCategory", "C");
tuple = new TupleDouble(oneResult);
result.add(tuple);
final Map<String, List<Tuple>> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE);
assertEquals(2, act.size());
assertNotNull(act.get("1"));
assertNotNull(act.get("2"));
assertEquals(1, act.get("2").size());
assertEquals("C", act.get("2").get(0).get("RoleCategory"));
}
@Test
void checkConvertOneResultCompoundKey() throws ODataJPAModelException, ODataApplicationException {
final JPAAssociationPath exp = helper.getJPAAssociationPath("AdministrativeDivisions", "Parent");
final List<Tuple> result = new ArrayList<>();
final HashMap<String, Object> oneResult = new HashMap<>();
oneResult.put("CodePublisher", "NUTS");
oneResult.put("DivisionCode", "BE25");
oneResult.put("CodeID", "2");
oneResult.put("ParentCodeID", "1");
oneResult.put("ParentDivisionCode", "BE2");
final Tuple tuple = new TupleDouble(oneResult);
result.add(tuple);
final Map<String, List<Tuple>> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE);
assertNotNull(act.get("NUTS/2/BE25"));
assertEquals(1, act.get("NUTS/2/BE25").size());
assertEquals("BE2", act.get("NUTS/2/BE25").get(0).get("ParentDivisionCode"));
}
@Test
void checkConvertTwoResultsCompoundKey() throws ODataJPAModelException, ODataApplicationException {
final JPAAssociationPath exp = helper.getJPAAssociationPath("AdministrativeDivisions", "Parent");
final List<Tuple> result = new ArrayList<>();
HashMap<String, Object> oneResult;
Tuple tuple;
oneResult = new HashMap<>();
oneResult.put("CodePublisher", "NUTS");
oneResult.put("DivisionCode", "BE25");
oneResult.put("CodeID", "2");
oneResult.put("ParentCodeID", "1");
oneResult.put("ParentDivisionCode", "BE2");
tuple = new TupleDouble(oneResult);
result.add(tuple);
oneResult = new HashMap<>();
oneResult.put("CodePublisher", "NUTS");
oneResult.put("DivisionCode", "BE10");
oneResult.put("CodeID", "2");
oneResult.put("ParentCodeID", "1");
oneResult.put("ParentDivisionCode", "BE1");
tuple = new TupleDouble(oneResult);
result.add(tuple);
final Map<String, List<Tuple>> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE);
assertEquals(2, act.size());
assertNotNull(act.get("NUTS/2/BE25"));
assertEquals(1, act.get("NUTS/2/BE25").size());
assertEquals("BE2", act.get("NUTS/2/BE25").get(0).get("ParentDivisionCode"));
assertNotNull(act.get("NUTS/2/BE10"));
assertEquals(1, act.get("NUTS/2/BE10").size());
assertEquals("BE1", act.get("NUTS/2/BE10").get(0).get("ParentDivisionCode"));
}
@Test
void checkConvertOneResultJoinTable() throws ODataException {
final JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "SupportEngineers");
final EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "Person");
cut = new JPAExpandJoinQuery(null, helper.getJPAAssociationPath("Organizations",
"SupportEngineers"), helper.sd.getEntity(targetEntity), requestContext);
final List<Tuple> result = new ArrayList<>();
final HashMap<String, Object> oneResult = new HashMap<>();
oneResult.put("SupportEngineers" + JPAAbstractJoinQuery.ALIAS_SEPARATOR + "ID", "2");
oneResult.put("ID", "97");
final Tuple tuple = new TupleDouble(oneResult);
result.add(tuple);
final Map<String, List<Tuple>> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE);
assertNotNull(act.get("2"));
assertEquals(1, act.get("2").size());
assertEquals("97", act.get("2").get(0).get("ID"));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAKeyPairTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAKeyPairTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import jakarta.persistence.AttributeConverter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives.UuidSortOrder;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAKeyPairException;
import com.sap.olingo.jpa.processor.core.testmodel.UUIDToBinaryConverter;
import com.sap.olingo.jpa.processor.core.testmodel.UUIDToStringConverter;
@SuppressWarnings("rawtypes")
class JPAKeyPairTest {
private JPAKeyPair cut;
private JPAAttribute attribute1;
private JPAAttribute attribute2;
private JPAAttribute attribute3;
private Map<JPAAttribute, Comparable> key1;
private Map<JPAAttribute, Comparable> key2;
private Map<JPAAttribute, Comparable> key3;
private List<JPAAttribute> keyDef;
private JPAODataQueryDirectives directives;
@BeforeEach
void setup() {
directives = new JPAODataQueryDirectives.JPAODataQueryDirectivesImpl(0, UuidSortOrder.AS_STRING);
attribute1 = mock(JPAAttribute.class);
attribute2 = mock(JPAAttribute.class);
attribute3 = mock(JPAAttribute.class);
key1 = new HashMap<>(3);
key2 = new HashMap<>(3);
key3 = new HashMap<>(3);
keyDef = new ArrayList<>(3);
keyDef.add(attribute1);
cut = new JPAKeyPair(keyDef, directives);
key1.put(attribute1, Integer.valueOf(10));
key2.put(attribute1, Integer.valueOf(100));
}
@Test
void testCreatePairWithOnlyOneValue() {
assertNotNull(cut);
}
@Test
void testToStringContainsMinMax() throws ODataJPAKeyPairException {
cut.setValue(key1);
cut.setValue(key2);
final String act = cut.toString();
assertTrue(act.contains("10"));
assertTrue(act.contains("100"));
}
@Test
void testCreatePairWithOneValues() throws ODataJPAKeyPairException {
cut.setValue(key1);
assertFalse(cut.hasUpperBoundary());
assertEquals(10, cut.getMin().get(attribute1));
}
@Test
void testCreatePairWithTwoValues() throws ODataJPAKeyPairException {
cut.setValue(key1);
cut.setValue(key2);
assertEquals(10, cut.getMin().get(attribute1));
assertEquals(100, cut.getMax().get(attribute1));
assertTrue(cut.hasUpperBoundary());
}
@Test
void testCreatePairWithTwoValuesSecondLower() throws ODataJPAKeyPairException {
cut.setValue(key2);
cut.setValue(key1);
assertEquals(10, cut.getMin().get(attribute1));
assertEquals(100, cut.getMax().get(attribute1));
assertTrue(cut.hasUpperBoundary());
}
@Test
void testCreatePairWithThirdValuesHigher() throws ODataJPAKeyPairException {
key3.put(attribute1, Integer.valueOf(101));
cut.setValue(key2);
cut.setValue(key1);
cut.setValue(key3);
assertEquals(10, cut.getMin().get(attribute1));
assertEquals(101, cut.getMax().get(attribute1));
}
@Test
void testCreatePairWithThirdValuesLower() throws ODataJPAKeyPairException {
key3.put(attribute1, Integer.valueOf(9));
cut.setValue(key2);
cut.setValue(key1);
cut.setValue(key3);
assertEquals(9, cut.getMin().get(attribute1));
assertEquals(100, cut.getMax().get(attribute1));
}
@Test
void testCreatePairWithThirdValuesBetween() throws ODataJPAKeyPairException {
key3.put(attribute1, Integer.valueOf(50));
cut.setValue(key2);
cut.setValue(key1);
cut.setValue(key3);
assertEquals(10, cut.getMin().get(attribute1));
assertEquals(100, cut.getMax().get(attribute1));
}
@Test
void testCreatePairWithOneCompound() throws ODataJPAKeyPairException {
fillKeyAttributes();
cut.setValue(createCompoundKey("A", "B", "C"));
assertFalse(cut.hasUpperBoundary());
assertEquals("A", cut.getMin().get(attribute1));
}
@Test
void testCreatePairWithTwoCompoundSame() throws ODataJPAKeyPairException {
fillKeyAttributes();
cut.setValue(createCompoundKey("A", "B", "C"));
cut.setValue(createCompoundKey("A", "B", "C"));
assertFalse(cut.hasUpperBoundary());
assertEquals("A", cut.getMin().get(attribute1));
}
@Test
void testCreatePairWithTwoCompoundLastBigger() throws ODataJPAKeyPairException {
fillKeyAttributes();
cut.setValue(createCompoundKey("A", "B", "C"));
cut.setValue(createCompoundKey("A", "B", "D"));
assertTrue(cut.hasUpperBoundary());
assertEquals("C", cut.getMin().get(attribute3));
assertEquals("D", cut.getMax().get(attribute3));
}
@Test
void testCreatePairWithTwoCompoundFirstBigger() throws ODataJPAKeyPairException {
fillKeyAttributes();
cut.setValue(createCompoundKey("A", "B", "C"));
cut.setValue(createCompoundKey("B", "B", "C"));
assertTrue(cut.hasUpperBoundary());
assertEquals("C", cut.getMin().get(attribute3));
assertEquals("C", cut.getMax().get(attribute3));
assertEquals("A", cut.getMin().get(attribute1));
assertEquals("B", cut.getMax().get(attribute1));
}
@Test
void testCreatePairWithThreeCompoundLastKeyBigger() throws ODataJPAKeyPairException {
fillKeyAttributes();
cut.setValue(createCompoundKey("A", "B", "C"));
cut.setValue(createCompoundKey("B", "A", "D"));
cut.setValue(createCompoundKey("C", "B", "C"));
assertTrue(cut.hasUpperBoundary());
assertEquals("C", cut.getMin().get(attribute3));
assertEquals("C", cut.getMax().get(attribute3));
assertEquals("A", cut.getMin().get(attribute1));
assertEquals("C", cut.getMax().get(attribute1));
}
@Test
void testCreatePairWithThreeCompoundSecondBigger() throws ODataJPAKeyPairException {
fillKeyAttributes();
cut.setValue(createCompoundKey("A", "B", "C"));
cut.setValue(createCompoundKey("C", "B", "C"));
cut.setValue(createCompoundKey("B", "A", "D"));
assertTrue(cut.hasUpperBoundary());
assertEquals("C", cut.getMin().get(attribute3));
assertEquals("C", cut.getMax().get(attribute3));
assertEquals("A", cut.getMin().get(attribute1));
assertEquals("C", cut.getMax().get(attribute1));
}
@Test
void testCreatePairWithThreeCompoundLastKeySmallest() throws ODataJPAKeyPairException {
fillKeyAttributes();
cut.setValue(createCompoundKey("B", "A", "D"));
cut.setValue(createCompoundKey("C", "B", "C"));
cut.setValue(createCompoundKey("A", "B", "C"));
assertTrue(cut.hasUpperBoundary());
assertEquals("C", cut.getMin().get(attribute3));
assertEquals("C", cut.getMax().get(attribute3));
assertEquals("A", cut.getMin().get(attribute1));
assertEquals("C", cut.getMax().get(attribute1));
}
@Test
void testCreatePairConversionString() {
final JPAAttribute attributeUUID = mock(JPAAttribute.class);
doReturn(new UUIDToStringConverter()).when(attributeUUID).getConverter();
doReturn(new UUIDToStringConverter()).when(attributeUUID).getRawConverter();
cut = new JPAKeyPair(Collections.singletonList(attributeUUID), directives);
Arrays.asList("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", "52a4eb6d-ab9d-4bc8-8405-5255d9607441",
"59ce6d1c-0770-48ae-b9ea-47c4ce9994c1", "9768b78c-e010-4e62-bada-8a138be7334d",
"e5406bb9-7166-4c0a-928c-f6deed6325bc").forEach(u -> addUUID(attributeUUID, u));
assertTrue(cut.hasUpperBoundary());
assertEquals("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", cut.getMinElement(attributeUUID).toString());
assertEquals("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", cut.getMin().get(attributeUUID).toString());
assertEquals("e5406bb9-7166-4c0a-928c-f6deed6325bc", cut.getMaxElement(attributeUUID).toString());
assertEquals("e5406bb9-7166-4c0a-928c-f6deed6325bc", cut.getMax().get(attributeUUID).toString());
}
@Test
void testCreatePairConversionByteArray() {
final JPAAttribute attributeUUID = mock(JPAAttribute.class);
doReturn(byte[].class).when(attributeUUID).getDbType();
doReturn(new UUIDToBinaryConverter()).when(attributeUUID).getConverter();
doReturn(new UUIDToBinaryConverter()).when(attributeUUID).getRawConverter();
cut = new JPAKeyPair(Collections.singletonList(attributeUUID), directives);
Arrays.asList("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", "52a4eb6d-ab9d-4bc8-8405-5255d9607441",
"59ce6d1c-0770-48ae-b9ea-47c4ce9994c1", "9768b78c-e010-4e62-bada-8a138be7334d",
"e5406bb9-7166-4c0a-928c-f6deed6325bc").forEach(u -> addUUID(attributeUUID, u));
assertTrue(cut.hasUpperBoundary());
assertEquals("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", cut.getMinElement(attributeUUID).toString());
assertEquals("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", cut.getMin().get(attributeUUID).toString());
assertEquals("9768b78c-e010-4e62-bada-8a138be7334d", cut.getMaxElement(attributeUUID).toString());
assertEquals("9768b78c-e010-4e62-bada-8a138be7334d", cut.getMax().get(attributeUUID).toString());
}
@Test
void testCreatePairConversionTargetNotComparable() throws ODataJPAKeyPairException {
final JPAAttribute attribute = mock(JPAAttribute.class);
doReturn(NotComparable.class).when(attribute).getDbType();
doReturn(new NotComparableConverter()).when(attribute).getConverter();
doReturn(new NotComparableConverter()).when(attribute).getRawConverter();
cut = new JPAKeyPair(Collections.singletonList(attribute), directives);
final Map<JPAAttribute, Comparable> key = new HashMap<>(3);
key.put(attribute, "Hallo");
cut.setValue(key);
assertThrows(ODataJPAKeyPairException.class, () -> cut.setValue(key));
}
@Test
void testCreatePairUuidSortedAsString() {
final JPAAttribute attributeUUID = mock(JPAAttribute.class);
cut = new JPAKeyPair(Collections.singletonList(attributeUUID), directives);
Arrays.asList("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", "52a4eb6d-ab9d-4bc8-8405-5255d9607441",
"59ce6d1c-0770-48ae-b9ea-47c4ce9994c1", "9768b78c-e010-4e62-bada-8a138be7334d",
"e5406bb9-7166-4c0a-928c-f6deed6325bc").forEach(u -> addUUID(attributeUUID, u));
assertTrue(cut.hasUpperBoundary());
assertEquals("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", cut.getMinElement(attributeUUID).toString());
assertEquals("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", cut.getMin().get(attributeUUID).toString());
assertEquals("e5406bb9-7166-4c0a-928c-f6deed6325bc", cut.getMaxElement(attributeUUID).toString());
assertEquals("e5406bb9-7166-4c0a-928c-f6deed6325bc", cut.getMax().get(attributeUUID).toString());
}
@Test
void testCreatePairUuidSortedAsByteArray() {
directives = new JPAODataQueryDirectives.JPAODataQueryDirectivesImpl(0, UuidSortOrder.AS_BYTE_ARRAY);
cut = new JPAKeyPair(keyDef, directives);
final JPAAttribute attributeUUID = mock(JPAAttribute.class);
cut = new JPAKeyPair(Collections.singletonList(attributeUUID), directives);
Arrays.asList("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", "52a4eb6d-ab9d-4bc8-8405-5255d9607441",
"59ce6d1c-0770-48ae-b9ea-47c4ce9994c1", "9768b78c-e010-4e62-bada-8a138be7334d",
"e5406bb9-7166-4c0a-928c-f6deed6325bc").forEach(u -> addUUID(attributeUUID, u));
assertTrue(cut.hasUpperBoundary());
assertEquals("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", cut.getMinElement(attributeUUID).toString());
assertEquals("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", cut.getMin().get(attributeUUID).toString());
assertEquals("9768b78c-e010-4e62-bada-8a138be7334d", cut.getMaxElement(attributeUUID).toString());
assertEquals("9768b78c-e010-4e62-bada-8a138be7334d", cut.getMax().get(attributeUUID).toString());
}
@Test
void testCreatePairUuidSortedAsUuid() {
directives = new JPAODataQueryDirectives.JPAODataQueryDirectivesImpl(0, UuidSortOrder.AS_JAVA_UUID);
cut = new JPAKeyPair(keyDef, directives);
final JPAAttribute attributeUUID = mock(JPAAttribute.class);
cut = new JPAKeyPair(Collections.singletonList(attributeUUID), directives);
Arrays.asList("400d7044-1e84-4e63-b2d9-0f58f4ca5bd0", "52a4eb6d-ab9d-4bc8-8405-5255d9607441",
"59ce6d1c-0770-48ae-b9ea-47c4ce9994c1", "9768b78c-e010-4e62-bada-8a138be7334d",
"e5406bb9-7166-4c0a-928c-f6deed6325bc").forEach(u -> addUUID(attributeUUID, u));
assertTrue(cut.hasUpperBoundary());
assertEquals("9768b78c-e010-4e62-bada-8a138be7334d", cut.getMinElement(attributeUUID).toString());
assertEquals("9768b78c-e010-4e62-bada-8a138be7334d", cut.getMin().get(attributeUUID).toString());
assertEquals("59ce6d1c-0770-48ae-b9ea-47c4ce9994c1", cut.getMaxElement(attributeUUID).toString());
assertEquals("59ce6d1c-0770-48ae-b9ea-47c4ce9994c1", cut.getMax().get(attributeUUID).toString());
}
private void addUUID(final JPAAttribute attributeUUID, final String uuid) {
final UUID id = UUID.fromString(uuid);
try {
cut.setValue(Collections.singletonMap(attributeUUID, id));
} catch (final ODataJPAKeyPairException e) {
fail();
}
}
private void fillKeyAttributes() {
keyDef.add(attribute2);
keyDef.add(attribute3);
}
private Map<JPAAttribute, Comparable> createCompoundKey(final String first, final String second,
final String third) {
final Map<JPAAttribute, Comparable> key = new HashMap<>(3);
key.put(attribute1, first);
key.put(attribute2, second);
key.put(attribute3, third);
return key;
}
private static class NotComparable {
}
private static class NotComparableConverter implements AttributeConverter<String, NotComparable> {
@Override
public NotComparable convertToDatabaseColumn(final String attribute) {
return new NotComparable();
}
@Override
public String convertToEntityAttribute(final NotComparable dbData) {
return "Test";
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.IOException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQueryJSONAnnotations extends TestBase {
@Test
void testEntityWithMetadataFullContainNavigationLink() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')?$format=application/json;odata.metadata=full");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("Roles@odata.navigationLink"));
assertEquals("Organizations('3')/Roles", org.get("Roles@odata.navigationLink").asText());
}
@Test
void testEntityWithMetadataMinimalWithoutNavigationLink() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')?$format=application/json;odata.metadata=minimal");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNull(org.get("Roles@odata.navigationLink"));
}
@Test
void testEntityWithMetadataNoneWithoutNavigationLink() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')?$format=application/json;odata.metadata=none");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNull(org.get("Roles@odata.navigationLink"));
}
@Test
void testEntityExpandWithMetadataFullContainNavigationLink() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')?$expand=Roles&$format=application/json;odata.metadata=full");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
assertNotNull(org.get("Roles@odata.navigationLink"));
assertEquals("Organizations('3')/Roles", org.get("Roles@odata.navigationLink").asText());
}
@Test
void testEntityWithMetadataFullContainNavigationLinkOfComplex() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')?$format=application/json;odata.metadata=full");
helper.assertStatus(200);
final ObjectNode org = helper.getValue();
final ObjectNode admin = (ObjectNode) org.get("AdministrativeInformation");
final ObjectNode created = (ObjectNode) admin.get("Created");
assertNotNull(created.get("User@odata.navigationLink"));
assertEquals("Organizations('3')/AdministrativeInformation/Created/User", created.get("User@odata.navigationLink")
.asText());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.util.TestDataConstants.NO_ATTRIBUTES_BUSINESS_PARTNER_T;
import static com.sap.olingo.jpa.processor.core.util.TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS;
import static com.sap.olingo.jpa.processor.core.util.TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS_T;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Selection;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.UriResourceValue;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerWithGroups;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.util.EdmEntityTypeDouble;
import com.sap.olingo.jpa.processor.core.util.EdmPropertyDouble;
import com.sap.olingo.jpa.processor.core.util.ExpandItemDouble;
import com.sap.olingo.jpa.processor.core.util.ExpandOptionDouble;
import com.sap.olingo.jpa.processor.core.util.SelectOptionDouble;
import com.sap.olingo.jpa.processor.core.util.TestQueryBase;
import com.sap.olingo.jpa.processor.core.util.UriInfoDouble;
import com.sap.olingo.jpa.processor.core.util.UriResourceNavigationDouble;
import com.sap.olingo.jpa.processor.core.util.UriResourcePropertyDouble;
class TestJPAQuerySelectClause extends TestQueryBase {
@Test
void checkSelectAll() throws ODataApplicationException, ODataJPAModelException {
fillJoinTable(root);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("*"))).joinedPersistent(), root, Collections.emptyList());
assertEquals(jpaEntityType.getPathList().size() - NO_ATTRIBUTES_BUSINESS_PARTNER_T.value, selectClause.size());
}
@Test
void checkSelectAllWithGroup() throws ODataJPAIllegalAccessException, ODataException {
jpaEntityType = helper.getJPAEntityType(BusinessPartnerWithGroups.class);
final SelectOption selectOption = new SelectOptionDouble("*");
buildUriInfo("BusinessPartnerWithGroupss", "BusinessPartnerWithGroups");
doReturn(selectOption).when(uriInfo).getSelectOption();
final String groupName = "Company";
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables = new HashMap<>();
joinTables.put(jpaEntityType.getExternalName(), root);
fillJoinTable(root);
requestContext = new JPAODataInternalRequestContext(externalContext, context, odata);
requestContext.setUriInfo(uriInfo);
cut = new JPAJoinQuery(null, requestContext);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
uriInfo).joinedPersistent(), root, List.of(groupName));
for (var selection : selectClause) {
if (selection.getAlias().equals("Country"))
fail("Unexpected element");
}
}
@Test
void checkSelectAllWithSelectionNull() throws ODataApplicationException, ODataJPAModelException {
fillJoinTable(root);
final SelectOption selOpts = null;
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(selOpts)).joinedPersistent(), root, Collections.emptyList());
assertEquals(jpaEntityType.getPathList().size() - NO_ATTRIBUTES_BUSINESS_PARTNER_T.value, selectClause.size());
}
@Test
void checkSelectExpandViaIgnoredProperties() throws ODataApplicationException {
// Organizations('3')/Address?$expand=AdministrativeDivision
fillJoinTable(root);
final List<ExpandItem> expItems = new ArrayList<>();
final EdmEntityType startEntity = new EdmEntityTypeDouble(nameBuilder, "Organization");
final EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "AdministrativeDivision");
final SelectOption selectOpts = null;
final ExpandOption expOpts = new ExpandOptionDouble("AdministrativeDivision", expItems);
expItems.add(new ExpandItemDouble(targetEntity));
final List<UriResource> startResources = new ArrayList<>();
final UriInfoDouble uriInfo = new UriInfoDouble(selectOpts);
uriInfo.setExpandOpts(expOpts);
uriInfo.setUriResources(startResources);
startResources.add(new UriResourceNavigationDouble(startEntity));
startResources.add(new UriResourcePropertyDouble(new EdmPropertyDouble("Address")));
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo)
.joinedPersistent(), root, Collections.emptyList());
assertContains(selectClause, "Address/RegionCodeID");
}
@Test
void checkSelectOnePropertyCreatedAt() throws ODataApplicationException {
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("CreationDateTime"))).joinedPersistent(), root, Collections
.emptyList());
assertEquals(3, selectClause.size());
assertContains(selectClause, "CreationDateTime");
assertContains(selectClause, "ID");
assertContains(selectClause, "ETag");
}
@Test
void checkSelectOnePropertyID() throws ODataApplicationException {
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("ID"))).joinedPersistent(), root, Collections.emptyList());
assertEquals(2, selectClause.size());
assertContains(selectClause, "ID");
assertContains(selectClause, "ETag");
}
@Test
void checkSelectOnePropertyPartKey() throws ODataException, ODataJPAIllegalAccessException {
jpaEntityType = helper.getJPAEntityType("AdministrativeDivisionDescriptions");
buildRequestContext("AdministrativeDivisionDescriptions", "AdministrativeDivisionDescription");
cut = new JPAJoinQuery(null, requestContext);
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble((new SelectOptionDouble("CodePublisher")))).joinedPersistent(), root, Collections
.emptyList());
assertEquals(4, selectClause.size());
assertContains(selectClause, "CodePublisher");
assertContains(selectClause, "CodeID");
assertContains(selectClause, "DivisionCode");
assertContains(selectClause, "Language");
}
@Test
void checkSelectPropertyTypeCreatedAt() throws ODataApplicationException {
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Type,CreationDateTime"))).joinedPersistent(), root, Collections
.emptyList());
assertEquals(4, selectClause.size());
assertContains(selectClause, "CreationDateTime");
assertContains(selectClause, "Type");
assertContains(selectClause, "ETag");
assertContains(selectClause, "ID");
}
@Test
void checkSelectSupertypePropertyTypeName2() throws ODataException, ODataJPAIllegalAccessException {
jpaEntityType = helper.getJPAEntityType("Organizations");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
buildRequestContext("Organizations", "Organization");
cut = new JPAJoinQuery(null, requestContext);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Type,Name2"))).joinedPersistent(), root, Collections.emptyList());
assertContains(selectClause, "Name2");
assertContains(selectClause, "Type");
assertContains(selectClause, "ID");
assertContains(selectClause, "ETag");
assertEquals(4, selectClause.size());
}
@Test
void checkSelectCompleteComplexType() throws ODataException {
// Organizations$select=Address
jpaEntityType = helper.getJPAEntityType("Organizations");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
fillJoinTable(root);
cut = new JPAJoinQuery(null, requestContext);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Address"))).joinedPersistent(), root, Collections.emptyList());
assertEquals(NO_ATTRIBUTES_POSTAL_ADDRESS.value + 2 - NO_ATTRIBUTES_POSTAL_ADDRESS_T.value, selectClause.size());
}
@Test
void checkSelectCompleteNestedComplexTypeLowLevel() throws ODataException {
// Organizations$select=Address
jpaEntityType = helper.getJPAEntityType("Organizations");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("AdministrativeInformation/Created"))).joinedPersistent(), root,
Collections.emptyList());
assertEquals(4, selectClause.size());
assertContains(selectClause, "AdministrativeInformation/Created/By");
assertContains(selectClause, "AdministrativeInformation/Created/At");
assertContains(selectClause, "ETag");
assertContains(selectClause, "ID");
}
@Test
void checkSelectCompleteNestedComplexTypeHighLevel() throws ODataException {
// Organizations$select=Address
jpaEntityType = helper.getJPAEntityType("Organizations");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("AdministrativeInformation"))).joinedPersistent(), root, Collections
.emptyList());
assertEquals(6, selectClause.size());
assertContains(selectClause, "AdministrativeInformation/Created/By");
assertContains(selectClause, "AdministrativeInformation/Created/At");
assertContains(selectClause, "AdministrativeInformation/Updated/By");
assertContains(selectClause, "AdministrativeInformation/Updated/At");
assertContains(selectClause, "ETag");
assertContains(selectClause, "ID");
}
@Test
void checkSelectElementOfComplexType() throws ODataException {
// Organizations$select=Address/Country
jpaEntityType = helper.getJPAEntityType("Organizations");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
// SELECT c.address.geocode FROM Company c WHERE c.name = 'Random House'
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Address/Country"))).joinedPersistent(), root, Collections
.emptyList());
assertContains(selectClause, "Address/Country");
assertContains(selectClause, "ID");
assertContains(selectClause, "ETag");
assertEquals(3, selectClause.size());
}
@Test
void checkSelectCollectionProperty() throws ODataException, ODataJPAIllegalAccessException {
// Organizations?$select=Comment
jpaEntityType = helper.getJPAEntityType("Organizations");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
fillJoinTable(root);
buildUriInfo("Organizations", "Organization");
requestContext = new JPAODataInternalRequestContext(externalContext, context, odata);
requestContext.setUriInfo(uriInfo);
cut = new JPAJoinQuery(null, requestContext);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Comment"))).joinedPersistent(), root, Collections.emptyList());
assertEquals(2, selectClause.size());
assertContains(selectClause, "ID");
assertContains(selectClause, "ETag");
}
@Test
void checkSelectTextJoinSingleAttribute() throws ODataException {
jpaEntityType = helper.getJPAEntityType("Organizations");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
fillJoinTable(root);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Address/CountryName"))).joinedPersistent(), root, Collections
.emptyList());
assertContains(selectClause, "Address/CountryName");
assertContains(selectClause, "ID");
assertContains(selectClause, "ETag");
assertEquals(3, selectClause.size());
}
@Test
void checkSelectTextJoinComplexType() throws ODataException {
jpaEntityType = helper.getJPAEntityType("Organizations");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
fillJoinTable(root);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Address"))).joinedPersistent(), root, Collections.emptyList());
assertEquals(NO_ATTRIBUTES_POSTAL_ADDRESS.value + 2 - NO_ATTRIBUTES_POSTAL_ADDRESS_T.value, selectClause
.size());
assertContains(selectClause, "Address/CountryName");
assertContains(selectClause, "ETag");
assertContains(selectClause, "ID");
}
@Test
void checkSelectStreamValueStatic() throws ODataException, ODataJPAIllegalAccessException {
jpaEntityType = helper.getJPAEntityType("PersonImages");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
buildRequestContext("PersonImages", "PersonImage");
cut = new JPAJoinQuery(null, requestContext);
final UriInfoDouble uriInfo = new UriInfoDouble(new SelectOptionDouble("Address"));
final List<UriResource> uriResources = new ArrayList<>();
uriInfo.setUriResources(uriResources);
uriResources.add(new UriResourceEntitySetDouble());
uriResources.add(new UriResourceValueDouble());
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo)
.joinedPersistent(), root, Collections.emptyList());
assertNotNull(selectClause);
assertContains(selectClause, "Image");
assertContains(selectClause, "ID");
}
@Test
void checkSelectStreamValueDynamic() throws ODataException, ODataJPAIllegalAccessException {
jpaEntityType = helper.getJPAEntityType("OrganizationImages");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
buildRequestContext("OrganizationImages", "OrganizationImage");
cut = new JPAJoinQuery(null, requestContext);
final UriInfoDouble uriInfo = new UriInfoDouble(new SelectOptionDouble("Address"));
final List<UriResource> uriResources = new ArrayList<>();
uriInfo.setUriResources(uriResources);
uriResources.add(new UriResourceEntitySetDouble());
uriResources.add(new UriResourceValueDouble());
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo)
.joinedPersistent(), root, Collections.emptyList());
assertNotNull(selectClause);
assertContains(selectClause, "Image");
assertContains(selectClause, "MimeType");
assertContains(selectClause, "ID");
}
@Test
void checkSelectPropertyValue() throws ODataException, ODataJPAIllegalAccessException {
jpaEntityType = helper.getJPAEntityType("PersonImages");
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
buildRequestContext("PersonImages", "PersonImage");
cut = new JPAJoinQuery(null, requestContext);
final SelectOption selOpts = null;
final UriInfoDouble uriInfo = new UriInfoDouble(selOpts);
final List<UriResource> uriResources = new ArrayList<>();
uriInfo.setUriResources(uriResources);
// PersonImages('99')/AdministrativeInformation/Created/By/$value
uriResources.add(new UriResourceEntitySetDouble());
uriResources.add(new UriResourceComplexPropertyDouble(new EdmPropertyDouble("AdministrativeInformation")));
uriResources.add(new UriResourceComplexPropertyDouble(new EdmPropertyDouble("Created")));
uriResources.add(new UriResourcePropertyDouble(new EdmPropertyDouble("By")));
uriResources.add(new UriResourceValueDouble());
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo)
.joinedPersistent(), root, Collections.emptyList());
assertNotNull(selectClause);
assertContains(selectClause, "AdministrativeInformation/Created/By");
assertContains(selectClause, "ID");
}
@Test
void checkSelectContainsJoinTable() throws ODataException {
// Organizations$select=Address
final JPAServiceDocument sd = mock(JPAServiceDocument.class);
final JPAAssociationPath association = mock(JPAAssociationPath.class);
final UriResourcePartTyped uriResource = mock(UriResourcePartTyped.class);
final JPAOnConditionItem onCondition = mock(JPAOnConditionItem.class);
final JPAPath idPath = mock(JPAPath.class);
when(association.hasJoinTable()).thenReturn(Boolean.TRUE);
when(association.getLeftColumnsList()).thenReturn(Collections.singletonList(idPath));
when(association.getJoinColumnsList()).thenReturn(Collections.singletonList(onCondition));
when(onCondition.getLeftPath()).thenReturn(idPath);
when(association.getAlias()).thenReturn("SupportEngineers");
when(idPath.getAlias()).thenReturn("Id");
jpaEntityType = helper.getJPAEntityType(Organization.class);
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables.put(jpaEntityType.getInternalName(), root);
fillJoinTable(root);
final Join<?, ?> join = root.join("supportEngineers", JoinType.LEFT);
joinTables.put("SupportEngineers", join);
when(uriResource.isCollection()).thenReturn(Boolean.TRUE);
final JPANavigationPropertyInfo navi = new JPANavigationPropertyInfo(sd, uriResource, association, uriInfo);
final JPAInlineItemInfo info = mock(JPAInlineItemInfo.class);
when(info.getExpandAssociation()).thenReturn(association);
when(info.getHops()).thenReturn(Collections.singletonList(navi));
when(info.getEntityType()).thenReturn(jpaEntityType);
navi.setFromClause(root);
cut = new JPAExpandJoinQuery(null, info, requestContext, Optional.empty());
final List<Selection<?>> selectClause = cut.createSelectClause(
joinTables,
cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Address"))).joinedPersistent(),
root,
Collections.emptyList());
assertTrue(selectClause.stream().filter(s -> "SupportEngineers.Id".equals(s.getAlias())).findFirst().isPresent());
}
private void assertContains(final List<Selection<?>> selectClause, final String alias) {
for (final Selection<?> selection : selectClause) {
if (selection.getAlias().equals(alias))
return;
}
fail(alias + " not found");
}
private static class UriResourceValueDouble implements UriResourceValue {
@Override
public UriResourceKind getKind() {
return UriResourceKind.value;
}
@Override
public String getSegmentValue() {
return null;
}
}
private static class UriResourceComplexPropertyDouble implements UriResourceComplexProperty {
private final EdmProperty property;
public UriResourceComplexPropertyDouble(final EdmProperty property) {
super();
this.property = property;
}
@Override
public EdmProperty getProperty() {
return property;
}
@Override
public EdmType getType() {
return unsupported();
}
@Override
public boolean isCollection() {
return unsupported();
}
@Override
public String getSegmentValue(final boolean includeFilters) {
return unsupported();
}
@Override
public String toString(final boolean includeFilters) {
return unsupported();
}
@Override
public UriResourceKind getKind() {
return unsupported();
}
@Override
public String getSegmentValue() {
return unsupported();
}
@Override
public EdmComplexType getComplexType() {
return unsupported();
}
@Override
public EdmComplexType getComplexTypeFilter() {
return unsupported();
}
private <T> T unsupported() {
fail();
return null;
}
}
private static class UriResourceEntitySetDouble implements UriResourceEntitySet {
@Override
public EdmType getType() {
return unsupported();
}
@Override
public boolean isCollection() {
return unsupported();
}
@Override
public String getSegmentValue(final boolean includeFilters) {
return unsupported();
}
@Override
public String toString(final boolean includeFilters) {
return unsupported();
}
@Override
public UriResourceKind getKind() {
return unsupported();
}
@Override
public String getSegmentValue() {
return unsupported();
}
@Override
public EdmEntitySet getEntitySet() {
return unsupported();
}
@Override
public EdmEntityType getEntityType() {
return unsupported();
}
@Override
public List<UriParameter> getKeyPredicates() {
return unsupported();
}
@Override
public EdmType getTypeFilterOnCollection() {
return unsupported();
}
@Override
public EdmType getTypeFilterOnEntry() {
return unsupported();
}
private <T> T unsupported() {
fail();
return null;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.apache.olingo.server.api.uri.UriResourceValue;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.util.SelectOptionDouble;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
import com.sap.olingo.jpa.processor.core.util.UriInfoDouble;
class TestJPAQueryBuildSelectionPathList extends TestBase {
private JPAAbstractJoinQuery cut;
private JPAODataSessionContextAccess sessionContext;
private UriInfo uriInfo;
private JPAODataInternalRequestContext requestContext;
private JPAODataRequestContext externalContext;
private OData odata;
@BeforeEach
void setup() throws ODataException, ODataJPAIllegalAccessException {
buildUriInfo("BusinessPartners", "BusinessPartner");
helper = new TestHelper(emf, PUNIT_NAME);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
createHeaders();
sessionContext = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages),
emf, dataSource, null, null, null);
odata = mock(OData.class);
externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(emf.createEntityManager());
requestContext = new JPAODataInternalRequestContext(externalContext, sessionContext, odata);
requestContext.setUriInfo(uriInfo);
cut = new JPAJoinQuery(null, requestContext);
}
private List<UriResource> buildUriInfo(final String esName, final String etName) {
uriInfo = mock(UriInfo.class);
final EdmEntitySet odataEs = mock(EdmEntitySet.class);
final EdmEntityType odataType = mock(EdmEntityType.class);
final List<UriResource> resources = new ArrayList<>();
final UriResourceEntitySet esResource = mock(UriResourceEntitySet.class);
when(uriInfo.getUriResourceParts()).thenReturn(resources);
when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(0));
when(esResource.getEntitySet()).thenReturn(odataEs);
when(esResource.getKind()).thenReturn(UriResourceKind.entitySet);
when(esResource.getType()).thenReturn(odataType);
when(odataEs.getName()).thenReturn(esName);
when(odataEs.getEntityType()).thenReturn(odataType);
when(odataType.getNamespace()).thenReturn(PUNIT_NAME);
when(odataType.getName()).thenReturn(etName);
resources.add(esResource);
return resources;
}
@Test
void checkSelectAllAsNoSelectionGiven() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(uriInfo).getODataSelections();
assertEquals(23, act.size());
}
@Test
void checkSelectAllAsStarGiven() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("*")))
.getODataSelections();
assertEquals(23, act.size());
}
@Test
void checkSelectPrimitiveWithKey() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Country")))
.getODataSelections();
assertEquals(3, act.size());
}
@Test
void checkSelectAllFromComplexWithKey() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Address")))
.getODataSelections();
assertEquals(11, act.size());
}
@Test
void checkSelectKeyNoDuplicates() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("ID")))
.getODataSelections();
assertEquals(2, act.size());
}
@Test
void checkSelectAllFromNavigationComplexPrimitiveWithKey() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble(
"Address/CountryName"))).getODataSelections();
assertEquals(3, act.size());
}
@Test
void checkSelectTwoPrimitiveWithKey() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble(
"Country,ETag"))).getODataSelections();
assertEquals(3, act.size());
}
@Test
void checkSelectAllFromComplexAndOnePrimitiveWithKey() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble(
"Address,ETag"))).getODataSelections();
assertEquals(11, act.size());
}
@Test
void checkSelectAllFromNavigateComplexPrimitiveAndOnePrimitiveWithKey() throws ODataApplicationException {
final Collection<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble(
"Address/CountryName,Country"))).getODataSelections();
assertEquals(4, act.size());
}
@Test
void checkSelectNavigationComplex() throws ODataException {
final List<UriResource> resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner");
final UriResourceComplexProperty complexResource = mock(UriResourceComplexProperty.class);
final EdmProperty property = mock(EdmProperty.class);
when(complexResource.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("AdministrativeInformation");
resourcePath.add(complexResource);
final Collection<JPAPath> act = cut.buildSelectionPathList(uriInfo).getODataSelections();
assertEquals(6, act.size());
}
@Test
void checkSelectNavigationComplexComplex() throws ODataException {
final List<UriResource> resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner");
final UriResourceComplexProperty adminInfoResource = mock(UriResourceComplexProperty.class);
final EdmProperty adminInfoProperty = mock(EdmProperty.class);
when(adminInfoResource.getProperty()).thenReturn(adminInfoProperty);
when(adminInfoProperty.getName()).thenReturn("AdministrativeInformation");
resourcePath.add(adminInfoResource);
final UriResourceComplexProperty createdResource = mock(UriResourceComplexProperty.class);
final EdmProperty createdProperty = mock(EdmProperty.class);
when(createdResource.getProperty()).thenReturn(createdProperty);
when(createdProperty.getName()).thenReturn("Created");
resourcePath.add(createdResource);
final Collection<JPAPath> act = cut.buildSelectionPathList(uriInfo).getODataSelections();
assertEquals(4, act.size());
}
@Test
void checkSelectNavigationComplexComplexProperty() throws ODataException {
final List<UriResource> resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner");
final UriResourceComplexProperty adminInfoResource = mock(UriResourceComplexProperty.class);
final EdmProperty adminInfoProperty = mock(EdmProperty.class);
when(adminInfoResource.getProperty()).thenReturn(adminInfoProperty);
when(adminInfoProperty.getName()).thenReturn("AdministrativeInformation");
resourcePath.add(adminInfoResource);
final UriResourceComplexProperty createdResource = mock(UriResourceComplexProperty.class);
final EdmProperty createdProperty = mock(EdmProperty.class);
when(createdResource.getProperty()).thenReturn(createdProperty);
when(createdProperty.getName()).thenReturn("Created");
resourcePath.add(createdResource);
final UriResourcePrimitiveProperty byResource = mock(UriResourcePrimitiveProperty.class);
final EdmProperty byProperty = mock(EdmProperty.class);
when(byResource.getProperty()).thenReturn(byProperty);
when(byProperty.getName()).thenReturn("By");
resourcePath.add(byResource);
final Collection<JPAPath> act = cut.buildSelectionPathList(uriInfo).getODataSelections();
assertEquals(3, act.size());
}
@Test
void checkSelectNavigationPropertyValue() throws ODataException {
final List<UriResource> resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner");
final UriResourcePrimitiveProperty byResource = mock(UriResourcePrimitiveProperty.class);
final EdmProperty byProperty = mock(EdmProperty.class);
when(byResource.getProperty()).thenReturn(byProperty);
when(byProperty.getName()).thenReturn("Country");
resourcePath.add(byResource);
final UriResourceValue valueResource = mock(UriResourceValue.class);
when(valueResource.getSegmentValue()).thenReturn(Utility.VALUE_RESOURCE.toLowerCase());
resourcePath.add(valueResource);
final Collection<JPAPath> act = cut.buildSelectionPathList(uriInfo).getODataSelections();
assertEquals(3, act.size());
}
@Test
void checkSelectNavigationComplexWithSelectPrimitive() throws ODataException {
final List<UriResource> resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner");
final UriResourceComplexProperty addressResource = mock(UriResourceComplexProperty.class);
final EdmProperty addressProperty = mock(EdmProperty.class);
when(addressResource.getProperty()).thenReturn(addressProperty);
when(addressProperty.getName()).thenReturn("Address");
resourcePath.add(addressResource);
final SelectOption selOptions = new SelectOptionDouble("CountryName");
when(uriInfo.getSelectOption()).thenReturn(selOptions);
final Collection<JPAPath> act = cut.buildSelectionPathList(uriInfo).getODataSelections();
assertEquals(3, act.size());
}
@Test
void checkSelectContainsVersionEvenSoIgnored() throws ODataApplicationException {
final List<UriResource> resourcePath = buildUriInfo("BusinessPartnerProtecteds", "BusinessPartnerProtected");
final UriResourcePrimitiveProperty byResource = mock(UriResourcePrimitiveProperty.class);
final EdmProperty byProperty = mock(EdmProperty.class);
when(byResource.getProperty()).thenReturn(byProperty);
when(byProperty.getName()).thenReturn("ID");
resourcePath.add(byResource);
final UriResourceValue valueResource = mock(UriResourceValue.class);
when(valueResource.getSegmentValue()).thenReturn(Utility.VALUE_RESOURCE.toLowerCase());
resourcePath.add(valueResource);
final Collection<JPAPath> act = cut.buildSelectionPathList(uriInfo).getODataSelections();
assertEquals(2, act.size());
for (final JPAPath actElement : act) {
if ("ETag".equals(actElement.getLeaf().getExternalName()))
return;
}
fail("ETag not found");
}
@Test
void checkSelectTransientAtComplexWithKey() throws ODataApplicationException {
final SelectionPathInfo<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble(
"Address/Street")));
assertEquals(2, act.getODataSelections().size());
assertEquals(1, act.getTransientSelections().size());
assertEquals(2, act.getRequiredSelections().size());
}
@Test
void checkSelectTransientWithKey() throws ODataException, ODataJPAIllegalAccessException {
buildUriInfo("Persons", "Person");
requestContext = new JPAODataInternalRequestContext(externalContext, sessionContext, odata);
requestContext.setUriInfo(uriInfo);
cut = new JPAJoinQuery(null, requestContext);
final SelectionPathInfo<JPAPath> act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble(
"FullName")));
assertEquals(2, act.getODataSelections().size());
assertEquals(1, act.getTransientSelections().size());
assertEquals(2, act.getRequiredSelections().size());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/SelectOptionUtilTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/SelectOptionUtilTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.stream.Stream;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.SelectItem;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
class SelectOptionUtilTest {
private JPAStructuredType jpaEntity;
private SelectItem sItem;
private UriInfoResource uriInfo;
@TestFactory
Stream<DynamicTest> testSelectAllTrue() {
final SelectOption selectNull = mock(SelectOption.class);
when(selectNull.getSelectItems()).thenReturn(null);
final SelectOption selectEmpty = mock(SelectOption.class);
when(selectEmpty.getSelectItems()).thenReturn(Collections.emptyList());
final SelectOption selectStar = mock(SelectOption.class);
final SelectItem starItem = mock(SelectItem.class);
when(selectStar.getSelectItems()).thenReturn(Collections.singletonList(starItem));
when(starItem.isStar()).thenReturn(true);
return Stream.of(
dynamicTest("Empty Items", () -> assertTrue(SelectOptionUtil.selectAll(selectStar))),
dynamicTest("Empty Items", () -> assertTrue(SelectOptionUtil.selectAll(selectEmpty))),
dynamicTest("Empty Items", () -> assertTrue(SelectOptionUtil.selectAll(selectNull))),
dynamicTest("Empty Items", () -> assertTrue(SelectOptionUtil.selectAll(null))));
}
@Test
void testSelectAllFalse() {
final SelectOption select = mock(SelectOption.class);
final SelectItem starItem = mock(SelectItem.class);
when(select.getSelectItems()).thenReturn(Collections.singletonList(starItem));
when(starItem.isStar()).thenReturn(false);
assertFalse(SelectOptionUtil.selectAll(select));
}
@Test
void testThrowsBadRequestPathNotFound() throws ODataJPAModelException {
jpaEntity = mock(JPAStructuredType.class);
when(jpaEntity.getPath(anyString())).thenReturn(null);
sItem = mock(SelectItem.class);
uriInfo = mock(UriInfoResource.class);
when(sItem.getResourcePath()).thenReturn(uriInfo);
when(uriInfo.getUriResourceParts()).thenReturn(Collections.emptyList());
final ODataJPAQueryException act = assertThrows(ODataJPAQueryException.class, () -> SelectOptionUtil
.selectItemAsPath(jpaEntity, "", sItem));
assertEquals(400, act.getStatusCode());
}
@Test
void testThrowsInternalServerPathThrowsException() throws ODataJPAModelException {
jpaEntity = mock(JPAStructuredType.class);
when(jpaEntity.getPath(anyString())).thenThrow(ODataJPAModelException.class);
sItem = mock(SelectItem.class);
uriInfo = mock(UriInfoResource.class);
when(sItem.getResourcePath()).thenReturn(uriInfo);
when(uriInfo.getUriResourceParts()).thenReturn(Collections.emptyList());
final ODataJPAQueryException act = assertThrows(ODataJPAQueryException.class, () -> SelectOptionUtil
.selectItemAsPath(jpaEntity, "", sItem));
assertEquals(500, act.getStatusCode());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/EdmEntitySetResultTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/EdmEntitySetResultTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmEntityContainer;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding;
import org.apache.olingo.server.api.uri.UriParameter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class EdmEntitySetResultTest {
private EdmBindingTargetResult cut;
private List<UriParameter> keys;
private EdmEntitySet es;
private EdmEntitySet est;
@BeforeEach
void setup() {
keys = new ArrayList<>();
es = mock(EdmEntitySet.class);
when(es.getName()).thenReturn("Persons");
est = mock(EdmEntitySet.class);
when(est.getName()).thenReturn("BusinessPartnerRoles");
}
@Test
void testGetEntitySetName() {
cut = new EdmBindingTargetResult(es, keys, "");
assertEquals("Persons", cut.getName());
}
@Test
void testGetEntitySetGetKeys() {
final UriParameter key = mock(UriParameter.class);
when(key.getName()).thenReturn("ID");
keys.add(key);
cut = new EdmBindingTargetResult(es, keys, "");
assertEquals(keys, cut.getKeyPredicates());
}
@Test
void testGetEntitySetGet() {
cut = new EdmBindingTargetResult(es, keys, "Roles");
assertEquals("Roles", cut.getNavigationPath());
}
@Test
void testDetermineTargetEntitySetWithNaviNull() {
when(es.getNavigationPropertyBindings()).thenReturn(null);
cut = new EdmBindingTargetResult(es, keys, null);
assertEquals(es, cut.getTargetEdmBindingTarget());
}
@Test
void testDetermineTargetEntitySetWithNaviEmpty() {
when(es.getNavigationPropertyBindings()).thenReturn(null);
cut = new EdmBindingTargetResult(es, keys, "");
assertEquals(es, cut.getTargetEdmBindingTarget());
}
// return edmEntitySet.getEntityContainer().getEntitySet(navi.getTarget());
@Test
void testDetermineTargetEntitySetWithNavigation() {
final EdmEntityContainer container = mock(EdmEntityContainer.class);
final List<EdmNavigationPropertyBinding> bindings = new ArrayList<>(2);
EdmNavigationPropertyBinding binding = mock(EdmNavigationPropertyBinding.class);
bindings.add(binding);
when(binding.getPath()).thenReturn("InhouseAddress");
binding = mock(EdmNavigationPropertyBinding.class);
bindings.add(binding);
when(binding.getPath()).thenReturn("Roles");
when(binding.getTarget()).thenReturn("BusinessPartnerRoles");
when(es.getEntityContainer()).thenReturn(container);
when(es.getNavigationPropertyBindings()).thenReturn(bindings);
when(container.getEntitySet("BusinessPartnerRoles")).thenReturn(est);
cut = new EdmBindingTargetResult(es, keys, "Roles");
assertEquals(es, cut.getEdmBindingTarget());
assertEquals(est, cut.getTargetEdmBindingTarget());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySingleton.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySingleton.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQuerySingleton extends TestBase {
@Test
void testSingletonReturnsNoValue() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Singleton");
helper.assertStatus(404);
}
@Test
void testSingletonCount() throws IOException, ODataException {
// Not supported by OData/Olingo
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Singleton/$count");
assertEquals(400, helper.getStatus());
}
@Test
void testSingletonReturnsValue() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "CurrentUser");
helper.assertStatus(200);
final ObjectNode act = helper.getValue();
assertEquals("97", act.get("ID").asText());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java | package com.sap.olingo.jpa.processor.core.query;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
class TestJPAFunction {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
protected static EntityManagerFactory emf;
protected static DataSource ds;
protected static boolean functionCreated;
protected Map<String, List<String>> headers;
@BeforeEach
void setup() {
ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB);
final Map<String, Object> properties = new HashMap<>();
properties.put("jakarta.persistence.nonJtaDataSource", ds);
emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties);
emf.getProperties();
}
@Disabled("The segment of an action or of a non-composable function must be the last resource-path segment.")
@Test
void testNavigationAfterFunctionNotAllowed() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds,
"Siblings(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')/Parent");
helper.assertStatus(501);
}
@Test
void testFunctionGenerateQueryString() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds,
"Siblings(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')");
helper.assertStatus(200);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/ComparableByteArrayTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/ComparableByteArrayTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class ComparableByteArrayTest {
private ComparableByteArray cut;
@Test
void testUnboxedArrayClass() {
final Byte[] arr = { 0x00, 0x01, 0x05 };
final byte[] act = ComparableByteArray.unboxedArray(arr);
for (int i = 0; i < arr.length; i++)
assertEquals(arr[i], act[i]);
}
@Test
void testUnboxedArrayType() {
final byte[] arr = { 0x00, 0x01, 0x05 };
final byte[] act = ComparableByteArray.unboxedArray(arr);
assertEquals(arr, act);
}
@Test
void testUnboxedArrayThrowsExceptionWrongType() {
final String[] arr = { "Hallo" };
assertThrows(IllegalArgumentException.class, () -> ComparableByteArray.unboxedArray(arr));
}
@Test
void testCompareToEqual() {
final byte[] arr = { 0x40, 0x41, 0x42 };
cut = new ComparableByteArray(arr);
assertEquals(0, cut.compareTo(arr));
}
@Test
void testCompareToLower() {
final byte[] arr = { 0x40, 0x41, 0x42 };
final byte[] other = { 0x41, 0x42, 0x43 };
cut = new ComparableByteArray(arr);
assertTrue(cut.compareTo(other) < 0);
}
@Test
void testCompareToGreater() {
final byte[] arr = { 0x41, 0x42, 0x43 };
final byte[] other = { 0x40, 0x41, 0x42 };
cut = new ComparableByteArray(arr);
assertTrue(cut.compareTo(other) > 0);
}
@Test
void testHashCodeNotZero() {
final byte[] arr = { 0x41, 0x42, 0x43 };
cut = new ComparableByteArray(arr);
assertNotEquals(0, cut.hashCode());
}
@Test
void testEqualTrue() {
final byte[] arr = { 0x41, 0x42, 0x43 };
cut = new ComparableByteArray(arr);
assertEquals(new ComparableByteArray(arr), cut);
}
@Test
void testEqualTrueSame() {
final byte[] arr = { 0x41, 0x42, 0x43 };
cut = new ComparableByteArray(arr);
assertEquals(cut, cut);
}
@Test
void testEqualFalse() {
final byte[] arr = { 0x41, 0x42, 0x43 };
final byte[] other = { 0x40, 0x41, 0x42 };
cut = new ComparableByteArray(arr);
assertNotEquals(new ComparableByteArray(other), cut);
}
@Test
void testEqualFalseOtherType() {
final byte[] arr = { 0x41, 0x42, 0x43 };
cut = new ComparableByteArray(arr);
assertNotEquals(cut, "Willi"); // NOSONAR
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationFilterQueryBuilderTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationFilterQueryBuilderTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.AbstractQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceCount;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceLambdaVariable;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.apache.olingo.server.api.uri.queryoption.expression.Binary;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.filter.JPACountExpression;
import com.sap.olingo.jpa.processor.core.filter.JPANullExpression;
import com.sap.olingo.jpa.processor.core.testmodel.InheritanceByJoinAccount;
import com.sap.olingo.jpa.processor.core.testmodel.InheritanceByJoinLockedSavingAccount;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
class JPANavigationFilterQueryBuilderTest {
private JPAServiceDocument sd;
private EntityManager em;
private UriResourcePartTyped uriResourceItem;
private JPAAbstractQuery parent;
private JPAAssociationPath association;
private VisitableExpression expression;
private From<?, ?> from;
private JPAODataClaimProvider claimsProvider;
private List<String> groups;
private CriteriaBuilder cb;
private JPANavigationPropertyInfoAccess navigationInfo;
private JPAODataRequestContextAccess context;
private JPAODataDatabaseOperations dbOperations;
private JPAEntityType et;
private EdmEntityType type;
private AbstractQuery<?> query;
private Subquery<Integer> subQuery;
private Root<Person> queryRoot;
private JPANavigationFilterQueryBuilder cut;
@SuppressWarnings("unchecked")
@BeforeEach
void setup() throws ODataJPAModelException {
sd = mock(JPAServiceDocument.class);
em = mock(EntityManager.class);
uriResourceItem = mock(UriResourcePartTyped.class);
parent = mock(JPAAbstractQuery.class);
association = mock(JPAAssociationPath.class);
from = mock(From.class);
claimsProvider = mock(JPAODataClaimProvider.class);
navigationInfo = mock(JPANavigationPropertyInfoAccess.class);
uriResourceItem = mock(UriResourceNavigation.class);
context = mock(JPAODataRequestContextAccess.class);
dbOperations = mock(JPAODataDatabaseOperations.class);
et = mock(JPAEntityType.class);
type = mock(EdmEntityType.class);
query = mock(AbstractQuery.class);
subQuery = mock(Subquery.class);
queryRoot = mock(Root.class);
cb = mock(CriteriaBuilder.class);
cut = new JPANavigationFilterQueryBuilder(cb);
when(uriResourceItem.getType()).thenReturn(type);
when(sd.getEntity(type)).thenReturn(et);
doReturn(Integer.class).when(et).getKeyType();
doReturn(Person.class).when(et).getTypeClass();
when(context.getOperationConverter()).thenReturn(dbOperations);
when(parent.getContext()).thenReturn(context);
when(parent.getLocale()).thenReturn(Locale.GERMANY);
doReturn(query).when(parent).getQuery();
when(query.subquery(Integer.class)).thenReturn(subQuery);
when(subQuery.from(Person.class)).thenReturn(queryRoot);
when(navigationInfo.getAssociationPath()).thenReturn(association);
when(navigationInfo.getUriResource()).thenReturn(uriResourceItem);
}
@Test
void testCreatesFilterQuery() throws ODataApplicationException, ODataJPAModelException {
final OData o = OData.newInstance();
buildAssociationPath();
cut.setOdata(o)
.setServiceDocument(sd)
.setEntityManager(em)
.setNavigationInfo(navigationInfo)
.setParent(parent)
.setFrom(from)
.setClaimsProvider(claimsProvider)
.setExpression(expression)
.setGroups(groups);
final JPAAbstractSubQuery act = cut.build();
assertTrue(act instanceof JPANavigationFilterQuery);
assertNotNull(act);
assertEquals(o, act.odata);
assertEquals(sd, act.sd);
assertEquals(em, act.em);
assertEquals(from, act.from);
assertEquals(parent, act.parentQuery);
assertEquals(association, act.association);
assertEquals(et, act.jpaEntity);
assertEquals(Locale.GERMANY, act.locale);
assertEquals(subQuery, act.subQuery);
assertTrue(act.claimsProvider.isPresent());
}
private static Stream<Arguments> provideCountExpressions() {
return Stream.of(
Arguments.of(buildCountFromCountExpression()));
}
@ParameterizedTest
@MethodSource("provideCountExpressions")
void testCreatesCountQuery(final VisitableExpression exp) throws ODataApplicationException, ODataJPAModelException {
final OData o = OData.newInstance();
final var associationPath = buildAssociationPath();
when(navigationInfo.getAssociationPath()).thenReturn(associationPath);
cut.setOdata(o)
.setServiceDocument(sd)
.setEntityManager(em)
.setNavigationInfo(navigationInfo)
.setParent(parent)
.setFrom(from)
.setClaimsProvider(claimsProvider)
.setExpression(exp)
.setGroups(groups);
final JPAAbstractSubQuery act = cut.build();
assertTrue(act instanceof JPANavigationCountQuery);
assertNotNull(act);
assertEquals(o, act.odata);
assertEquals(sd, act.sd);
assertEquals(em, act.em);
assertEquals(from, act.from);
assertEquals(parent, act.parentQuery);
assertEquals(association, act.association);
assertEquals(et, act.jpaEntity);
assertEquals(Locale.GERMANY, act.locale);
assertEquals(subQuery, act.subQuery);
assertTrue(act.claimsProvider.isPresent());
}
private static Stream<Arguments> provideNullExpressions() {
return Stream.of(
Arguments.of(buildNullFromNullExpression()));
}
@ParameterizedTest
@MethodSource("provideNullExpressions")
void testCreatesNullQuery(final VisitableExpression exp) throws ODataApplicationException, ODataJPAModelException {
final OData o = OData.newInstance();
final var associationPath = buildAssociationPath();
when(navigationInfo.getAssociationPath()).thenReturn(associationPath);
cut.setOdata(o)
.setServiceDocument(sd)
.setEntityManager(em)
.setNavigationInfo(navigationInfo)
.setParent(parent)
.setFrom(from)
.setClaimsProvider(claimsProvider)
.setExpression(exp)
.setGroups(groups);
final JPAAbstractSubQuery act = cut.build();
assertTrue(act instanceof JPANavigationNullQuery);
assertNotNull(act);
assertEquals(o, act.odata);
assertEquals(sd, act.sd);
assertEquals(em, act.em);
assertEquals(from, act.from);
assertEquals(parent, act.parentQuery);
assertEquals(association, act.association);
assertEquals(et, act.jpaEntity);
assertEquals(Locale.GERMANY, act.locale);
assertEquals(subQuery, act.subQuery);
assertTrue(act.claimsProvider.isPresent());
}
@Test
void testAsInQueryForProcessorCriteriaBuilder() throws ODataJPAFilterException {
cb = mock(ProcessorCriteriaBuilder.class);
cut = new JPANavigationFilterQueryBuilder(cb);
cut.setExpression(buildCountFromCountExpression());
assertTrue(cut.asInQuery());
}
@Test
void testAsExistsQueryForProcessorCriteriaBuilderNotCount() throws ODataJPAFilterException {
cb = mock(ProcessorCriteriaBuilder.class);
cut = new JPANavigationFilterQueryBuilder(cb);
assertFalse(cut.asInQuery());
}
@Test
void testAsInQueryTrueForCriteriaBuilderAssociationOneAttribute() throws ODataJPAModelException,
ODataJPAFilterException {
final JPAPath leftPath = mock(JPAPath.class);
final JPAAssociationPath associationPath = mock(JPAAssociationPath.class);
final JPAOnConditionItem onCondition = mock(JPAOnConditionItem.class);
when(associationPath.getJoinColumnsList()).thenReturn(Collections.singletonList(onCondition));
when(associationPath.getLeftColumnsList()).thenReturn(Collections.singletonList(leftPath));
when(navigationInfo.getAssociationPath()).thenReturn(associationPath);
cut.setNavigationInfo(navigationInfo);
cut.setExpression(buildCountFromCountExpression());
assertTrue(cut.asInQuery());
}
@Test
void testAsInQueryFalseForCriteriaBuilderAssociationTwoAttribute() throws ODataJPAModelException,
ODataJPAFilterException {
final var associationPath = buildAssociationPath();
when(navigationInfo.getAssociationPath()).thenReturn(associationPath);
cut.setNavigationInfo(navigationInfo);
cut.setExpression(buildCountFromCountExpression());
assertFalse(cut.asInQuery());
}
@Test
void testAsInQueryRethrowsException() throws ODataJPAModelException {
final JPAAssociationPath associationPath = mock(JPAAssociationPath.class);
when(associationPath.getLeftColumnsList()).thenThrow(ODataJPAModelException.class);
when(associationPath.getJoinColumnsList()).thenThrow(ODataJPAModelException.class);
when(navigationInfo.getAssociationPath()).thenReturn(associationPath);
cut.setNavigationInfo(navigationInfo);
assertThrows(ODataJPAFilterException.class, () -> cut.asInQuery());
}
@SuppressWarnings("unchecked")
@Test
void testPerformsTypeCastFromLambda() throws ODataJPAModelException, ODataApplicationException {
final OData o = OData.newInstance();
final var expFqn = new FullQualifiedName("com.sap.olingo.jpa.InheritanceLockedSavingAccount");
final var expEt = mock(JPAEntityType.class);
when(expEt.getExternalFQN()).thenReturn(expFqn);
doReturn(InheritanceByJoinLockedSavingAccount.class).when(expEt).getTypeClass();
doReturn(Integer.class).when(expEt).getKeyType();
final Root<InheritanceByJoinAccount> accountRoot = mock(Root.class);
final Root<InheritanceByJoinLockedSavingAccount> lockingRoot = mock(Root.class);
doReturn(InheritanceByJoinAccount.class).when(et).getTypeClass();
doReturn(new FullQualifiedName("com.sap.olingo.jpa.InheritanceAccount")).when(et).getExternalFQN();
when(subQuery.from(InheritanceByJoinAccount.class)).thenReturn(accountRoot);
when(subQuery.from(InheritanceByJoinLockedSavingAccount.class)).thenReturn(lockingRoot);
final JPAOnConditionItem onCondition = mock(JPAOnConditionItem.class);
final JPAElement pathItem = mock(JPAElement.class);
when(association.getJoinColumnsList()).thenReturn(Arrays.asList(onCondition, onCondition));
when(association.getPath()).thenReturn(Arrays.asList(pathItem));
when(association.getTargetType()).thenReturn(et);
final Binary exp = mock(Binary.class);
final UriInfoResource uriInfo = mock(UriInfoResource.class);
final UriResourceLambdaVariable lambdaVar = mock(UriResourceLambdaVariable.class);
final UriResourcePrimitiveProperty property = mock(UriResourcePrimitiveProperty.class);
final Literal right = mock(Literal.class);
final Member left = mock(Member.class);
when(exp.getRightOperand()).thenReturn(right);
when(exp.getLeftOperand()).thenReturn(left);
when(exp.getOperator()).thenReturn(BinaryOperatorKind.GT);
when(left.getResourcePath()).thenReturn(uriInfo);
when(uriInfo.getUriResourceParts()).thenReturn(List.of(lambdaVar, property));
when(lambdaVar.getSegmentValue(true)).thenReturn("s/com.sap.olingo.jpa.InheritanceLockedSavingAccount");
// ((UriResourceLambdaVariable)((Member)((Binary)expression).getLeftOperand()).getResourcePath().getUriResourceParts().get(0)).getSegmentValue(true)
when(sd.getEntity(expFqn)).thenReturn(expEt);
cut.setOdata(o)
.setServiceDocument(sd)
.setEntityManager(em)
.setNavigationInfo(navigationInfo)
.setParent(parent)
.setFrom(from)
.setClaimsProvider(claimsProvider)
.setExpression(exp)
.setGroups(groups);
final JPAAbstractSubQuery act = cut.build();
assertTrue(act instanceof JPANavigationFilterQuery);
assertEquals(expFqn, act.jpaEntity.getExternalFQN());
}
private JPAAssociationPath buildAssociationPath() throws ODataJPAModelException {
final JPAOnConditionItem onCondition = mock(JPAOnConditionItem.class);
final JPAElement pathItem = mock(JPAElement.class);
when(association.getJoinColumnsList()).thenReturn(Arrays.asList(onCondition, onCondition));
when(association.getPath()).thenReturn(Arrays.asList(pathItem));
return association;
}
private static VisitableExpression buildCountFromCountExpression() {
final UriInfoResource uriInfo = mock(UriInfoResource.class);
final JPACountExpression exp = mock(JPACountExpression.class);
final UriResourceCount countPart = mock(UriResourceCount.class);
final UriResourceNavigation navigationPart = mock(UriResourceNavigation.class);
final List<UriResource> resources = new ArrayList<>();
when(exp.getMember()).thenReturn(uriInfo);
when(uriInfo.getUriResourceParts()).thenReturn(resources);
when(navigationPart.getKind()).thenReturn(UriResourceKind.navigationProperty);
when(countPart.getKind()).thenReturn(UriResourceKind.count);
resources.add(navigationPart);
resources.add(countPart);
return exp;
}
private static VisitableExpression buildNullFromNullExpression() {
final Literal literal = mock(Literal.class);
final UriInfoResource uriInfo = mock(UriInfoResource.class);
final UriResourceNavigation navigationPart = mock(UriResourceNavigation.class);
final List<UriResource> resources = new ArrayList<>();
final JPANullExpression exp = mock(JPANullExpression.class);
when(exp.getMember()).thenReturn(uriInfo);
when(exp.getLiteral()).thenReturn(literal);
when(uriInfo.getUriResourceParts()).thenReturn(resources);
when(navigationPart.getKind()).thenReturn(UriResourceKind.navigationProperty);
when(literal.getText()).thenReturn("null");
return exp;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPACollectionQueryResultTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPACollectionQueryResultTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAODataPageExpandInfo;
class JPACollectionQueryResultTest {
private JPACollectionQueryResult cut;
private JPAAssociationPath associationPath;
private JPAEntityType entityType;
@BeforeEach
void setup() {
associationPath = mock(JPAAssociationPath.class);
entityType = mock(JPAEntityType.class);
cut = new JPACollectionQueryResult(entityType, associationPath, Collections.emptyList());
}
@Test
void testGetSkipTokenReturnsNull() {
assertNull(cut.getSkipToken(Collections.singletonList(new JPAODataPageExpandInfo("Test", "17"))));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryTopSkip.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryTopSkip.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Optional;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.debug.DefaultDebugSupport;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.processor.core.api.JPAODataApiVersionAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataServiceContext;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.util.Assertions;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQueryTopSkip extends TestBase {
@Test
void testTop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$top=10");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = ((ArrayNode) collection.get("value"));
assertEquals(10, act.size());
assertEquals("Eurostat", act.get(0).get("CodePublisher").asText());
assertEquals("LAU2", act.get(0).get("CodeID").asText());
assertEquals("31003", act.get(0).get("DivisionCode").asText());
}
@Test
void testSkip() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$skip=5");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = ((ArrayNode) collection.get("value"));
assertEquals(243, act.size());
assertEquals("Eurostat", act.get(0).get("CodePublisher").asText());
assertEquals("LAU2", act.get(0).get("CodeID").asText());
assertEquals("31022", act.get(0).get("DivisionCode").asText());
}
@Test
void testTopSkip() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$skip=5&$top=5");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = ((ArrayNode) collection.get("value"));
assertEquals(5, act.size());
assertEquals("Eurostat", act.get(0).get("CodePublisher").asText());
assertEquals("LAU2", act.get(0).get("CodeID").asText());
assertEquals("31022", act.get(0).get("DivisionCode").asText());
}
@Test
void testTopReturnsAllIfToLarge() throws IOException, ODataException {
final OData odata = OData.newInstance();
final var sessionContext = JPAODataServiceContext.with()
.setPUnit(IntegrationTestHelper.PUNIT_NAME)
.setEntityManagerFactory(emf)
.setRequestMappingPath("bp/v1")
.setTypePackage(TestBase.enumPackages)
.build();
final JPAODataRequestContext externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(emf.createEntityManager());
when(externalContext.getClaimsProvider()).thenReturn(Optional.empty());
when(externalContext.getGroupsProvider()).thenReturn(Optional.empty());
when(externalContext.getDebuggerSupport()).thenReturn(new DefaultDebugSupport());
when(externalContext.getRequestParameter()).thenReturn(mock(JPARequestParameterMap.class));
final var requestContext = new JPAODataInternalRequestContext(externalContext, sessionContext, odata);
final var handler = odata.createHandler(odata.createServiceMetadata(sessionContext
.getApiVersion(JPAODataApiVersionAccess.DEFAULT_VERSION).getEdmProvider(),
new ArrayList<>()));
final var request = IntegrationTestHelper.getRequestMock(IntegrationTestHelper.URI_PREFIX + "Persons?$top=5000");
final var response = IntegrationTestHelper.getResponseMock();
handler.register(new JPAODataRequestProcessor(sessionContext, requestContext));
handler.process(request, response);
final ObjectMapper mapper = new ObjectMapper();
final ObjectNode value = (ObjectNode) mapper.readTree(getRawResult(response));
assertNull(value.get("@odata.nextLink"));
}
@Tag(Assertions.CB_ONLY_TEST)
@Test
void testExpandTopSkipWithoutError() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$skip=5&$top=5&$expand=Children");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = ((ArrayNode) collection.get("value"));
assertEquals(5, act.size());
}
public String getRawResult(final HttpServletResponse response) throws IOException {
final InputStream in = asInputStream(response);
final StringBuilder builder = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String read;
while ((read = reader.readLine()) != null) {
builder.append(read);
}
reader.close();
return builder.toString();
}
public InputStream asInputStream(final HttpServletResponse response) throws IOException {
return new IntegrationTestHelper.ResultStream((IntegrationTestHelper.OutPutStream) response.getOutputStream());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationFilterQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationFilterQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRoleProtected;
import com.sap.olingo.jpa.processor.core.testmodel.JoinPartnerRoleRelation;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
class JPANavigationFilterQueryTest extends TestBase {
protected JPAAbstractSubQuery cut;
protected TestHelper helper;
protected EntityManager em;
protected OData odata;
protected UriResourceNavigation uriResourceItem;
protected JPAAbstractQuery parent;
protected JPAAssociationPath association;
protected From<?, ?> from;
protected Root<JoinPartnerRoleRelation> queryJoinTable;
protected Root<BusinessPartnerRoleProtected> queryRoot;
protected JPAODataClaimProvider claimsProvider;
protected JPAEntityType jpaEntityType;
@SuppressWarnings("rawtypes")
protected CriteriaQuery cq;
protected CriteriaBuilder cb;
protected Subquery<Object> subQuery;
@SuppressWarnings("unchecked")
@BeforeEach
void setup() throws ODataException {
helper = getHelper();
em = mock(EntityManager.class);
parent = mock(JPAAbstractQuery.class);
association = helper.getJPAAssociationPath(BusinessPartnerProtected.class, "RolesJoinProtected");
claimsProvider = mock(JPAODataClaimProvider.class);
odata = OData.newInstance();
uriResourceItem = mock(UriResourceNavigation.class);
jpaEntityType = helper.getJPAEntityType(BusinessPartnerRoleProtected.class);
cq = mock(CriteriaQuery.class);
cb = mock(CriteriaBuilder.class);
subQuery = mock(Subquery.class);
queryJoinTable = mock(Root.class);
queryRoot = mock(Root.class);
from = mock(From.class);
final UriParameter key = mock(UriParameter.class);
when(em.getCriteriaBuilder()).thenReturn(cb);
when(uriResourceItem.getKeyPredicates()).thenReturn(Collections.singletonList(key));
when(parent.getQuery()).thenReturn(cq);
when(cq.subquery(any(Class.class))).thenReturn(subQuery);
when(subQuery.from(JoinPartnerRoleRelation.class)).thenReturn(queryJoinTable);
when(subQuery.from(BusinessPartnerRoleProtected.class)).thenReturn(queryRoot);
when(claimsProvider.get("RoleCategory")).thenReturn(Collections.singletonList(new JPAClaimsPair<>("A")));
doReturn(BusinessPartnerProtected.class).when(from).getJavaType();
}
protected JPAAbstractSubQuery createCut() throws ODataApplicationException {
return new JPANavigationFilterQuery(odata, helper.sd, jpaEntityType,
parent, em, association, from, Optional.of(claimsProvider), Collections.emptyList());
}
@Test
void testCutExists() throws ODataApplicationException {
cut = createCut();
assertNotNull(cut);
}
@SuppressWarnings("unchecked")
@Test
void testJoinQueryWithClaim() throws ODataApplicationException {
final Path<Object> keyPath = mock(Path.class);
final Path<Object> sourcePath = mock(Path.class);
final Path<Object> targetPath = mock(Path.class);
final Path<Object> roleIdPath = mock(Path.class);
final Path<Object> roleCategoryPath = mock(Path.class);
final Path<Object> idPath = mock(Path.class);
final Predicate equalExpression1 = mock(Predicate.class);
final Predicate equalExpression2 = mock(Predicate.class);
final Predicate equalExpression3 = mock(Predicate.class);
final Predicate andExpression1 = mock(Predicate.class);
final Predicate andExpression2 = mock(Predicate.class);
when(queryJoinTable.get("key")).thenReturn(keyPath);
when(keyPath.get("sourceID")).thenReturn(sourcePath);
when(keyPath.get("targetID")).thenReturn(targetPath);
when(from.get("iD")).thenReturn(idPath);
when(cb.equal(idPath, sourcePath)).thenReturn(equalExpression1);
when(cb.equal(sourcePath, idPath)).thenReturn(equalExpression1);
when(queryRoot.get("businessPartnerID")).thenReturn(roleIdPath);
when(queryRoot.get("roleCategory")).thenReturn(roleCategoryPath);
when(queryRoot.get("iD")).thenReturn(idPath);
when(cb.equal(idPath, sourcePath)).thenReturn(equalExpression1);
when(cb.equal(sourcePath, idPath)).thenReturn(equalExpression1);
when(cb.equal(roleIdPath, sourcePath)).thenReturn(equalExpression2);
when(cb.equal(sourcePath, roleIdPath)).thenReturn(equalExpression2);
when(cb.equal(roleCategoryPath, targetPath)).thenReturn(equalExpression3);
when(cb.equal(targetPath, roleCategoryPath)).thenReturn(equalExpression3);
when(cb.and(equalExpression2, equalExpression3)).thenReturn(andExpression1);
when(cb.and(equalExpression1, andExpression1)).thenReturn(andExpression2);
cut = createCut();
@SuppressWarnings("unused")
final Subquery<Object> act = cut.getSubQuery(subQuery, null, Collections.emptyList());
verify(subQuery).select(roleIdPath);
verify(subQuery).where(andExpression2);
verify(cb).equal(roleCategoryPath, targetPath);
verify(cb).equal(roleCategoryPath, "A");
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import org.apache.olingo.commons.api.data.Annotatable;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmParameter;
import org.apache.olingo.commons.api.edm.EdmReturnType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.processor.JPAFunctionRequestProcessor;
import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionParameter;
class TestJPAFunctionJava {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
private JPAFunctionRequestProcessor cut;
private OData odata;
private JPAODataRequestContextAccess requestContext;
private UriInfo uriInfo;
private List<UriResource> uriResources;
private ODataRequest request;
private ODataResponse response;
private UriResourceFunction uriResource;
private EdmFunction edmFunction;
private JPAOperationSerializer serializer;
private SerializerResult serializerResult;
@BeforeEach
void setup() throws ODataException {
odata = mock(OData.class);
requestContext = mock(JPAODataRequestContextAccess.class);
final EntityManager em = mock(EntityManager.class);
uriInfo = mock(UriInfo.class);
serializer = mock(JPAOperationSerializer.class);
serializerResult = mock(SerializerResult.class);
final DataSource ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB);
final Map<String, Object> properties = new HashMap<>();
properties.put("jakarta.persistence.nonJtaDataSource", ds);
final EntityManagerFactory emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties);
uriResources = new ArrayList<>();
when(uriInfo.getUriResourceParts()).thenReturn(uriResources);
when(requestContext.getEdmProvider()).thenReturn(new JPAEdmProvider(PUNIT_NAME, emf, null, new String[] {
"com.sap.olingo.jpa.processor.core", "com.sap.olingo.jpa.processor.core.testmodel" }));
when(requestContext.getUriInfo()).thenReturn(uriInfo);
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getSerializer()).thenReturn(serializer);
when(serializer.serialize(any(Annotatable.class), any(EdmType.class), any(ODataRequest.class)))
.thenReturn(serializerResult);
request = mock(ODataRequest.class);
response = mock(ODataResponse.class);
uriResource = mock(UriResourceFunction.class);
edmFunction = mock(EdmFunction.class);
uriResources.add(uriResource);
when(uriResource.getFunction()).thenReturn(edmFunction);
cut = new JPAFunctionRequestProcessor(odata, requestContext);
}
@AfterEach
void teardown() {
TestFunctionParameter.calls = 0;
TestFunctionParameter.param1 = 0;
TestFunctionParameter.param2 = 0;
}
@Test
void testCallsFunction() throws ODataApplicationException, ODataLibraryException {
final EdmParameter edmParamA = mock(EdmParameter.class);
final EdmParameter edmParamB = mock(EdmParameter.class);
final EdmReturnType edmReturn = mock(EdmReturnType.class);
final EdmType edmType = mock(EdmType.class);
when(edmFunction.getReturnType()).thenReturn(edmReturn);
when(edmFunction.getName()).thenReturn("Sum");
when(edmFunction.getNamespace()).thenReturn(PUNIT_NAME);
when(edmFunction.getParameter("A")).thenReturn(edmParamA);
when(edmParamA.getType()).thenReturn(new EdmInt32());
when(edmFunction.getParameter("B")).thenReturn(edmParamB);
when(edmParamB.getType()).thenReturn(new EdmInt32());
final List<UriParameter> parameterList = buildParameters();
when(uriResource.getParameters()).thenReturn(parameterList);
when(edmReturn.getType()).thenReturn(edmType);
when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE);
cut.retrieveData(request, response, ContentType.JSON);
assertEquals(1, TestFunctionParameter.calls);
}
@Test
void testProvidesParameter() throws ODataApplicationException, ODataLibraryException {
final EdmParameter edmParamA = mock(EdmParameter.class);
final EdmParameter edmParamB = mock(EdmParameter.class);
final EdmReturnType edmReturn = mock(EdmReturnType.class);
final EdmType edmType = mock(EdmType.class);
when(edmFunction.getReturnType()).thenReturn(edmReturn);
when(edmFunction.getName()).thenReturn("Sum");
when(edmFunction.getNamespace()).thenReturn(PUNIT_NAME);
when(edmFunction.getParameter("A")).thenReturn(edmParamA);
when(edmParamA.getType()).thenReturn(new EdmInt32());
when(edmFunction.getParameter("B")).thenReturn(edmParamB);
when(edmParamB.getType()).thenReturn(new EdmInt32());
final List<UriParameter> parameterList = buildParameters();
when(uriResource.getParameters()).thenReturn(parameterList);
when(edmReturn.getType()).thenReturn(edmType);
when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE);
cut.retrieveData(request, response, ContentType.JSON);
assertEquals(5, TestFunctionParameter.param1);
assertEquals(7, TestFunctionParameter.param2);
}
private List<UriParameter> buildParameters() {
final UriParameter param1 = mock(UriParameter.class);
final UriParameter param2 = mock(UriParameter.class);
when(param1.getName()).thenReturn("A");
when(param1.getText()).thenReturn("5");
when(param2.getName()).thenReturn("B");
when(param2.getText()).thenReturn("7");
return Arrays.asList(param1, param2);
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.sap.olingo.jpa.metadata.odata.v4.provider.JavaBasedCapabilitiesAnnotationsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataExpandPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataPageExpandInfo;
import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
import com.sap.olingo.jpa.processor.core.util.Assertions;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAProcessorExpand extends TestBase {
@BeforeAll
static void classSetup() {
System.setProperty("organization.slf4j.simpleLogger.log.com.sap.olingo.jpa.processor.core.query", "TRACE");
}
@Test
void testExpandEntitySet() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$orderby=ID&$expand=Roles");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
ObjectNode organization = (ObjectNode) organizations.get(0);
ArrayNode roles = (ArrayNode) organization.get("Roles");
assertEquals(1, roles.size());
organization = (ObjectNode) organizations.get(3);
roles = (ArrayNode) organization.get("Roles");
assertEquals(3, roles.size());
}
@Test
void testExpandCompleteEntitySet2() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "AdministrativeDivisions?$expand=Parent");
helper.assertStatus(200);
}
@Test
void testExpandOneEntity() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('2')?$expand=Roles");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
final ArrayNode roles = (ArrayNode) organization.get("Roles");
assertEquals(2, roles.size());
int found = 0;
for (final JsonNode role : roles) {
final String id = role.get("BusinessPartnerID").asText();
final String code = role.get("RoleCategory").asText();
if (id.equals("2") && (code.equals("A") || code.equals("C")))
found++;
}
assertEquals(2, found, "Not all expected results found");
}
@Test
void testExpandOneEntityCompoundKey() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent");
helper.assertStatus(200);
final ObjectNode division = helper.getValue();
final ObjectNode parent = (ObjectNode) division.get("Parent");
assertEquals("BE2", parent.get("DivisionCode").asText());
}
@Test
void testExpandOneEntityCompoundKeyCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode asc)");
helper.assertStatus(200);
final ObjectNode division = helper.getValue();
final ArrayNode parent = (ArrayNode) division.get("Children");
assertEquals(8, parent.size());
assertEquals("BE251", parent.get(0).get("DivisionCode").asText());
}
@Test
void testExpandEntitySetWithOutParentKeySelection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$orderby=Name1&$select=Name1&$expand=Roles");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
final ObjectNode organization = (ObjectNode) organizations.get(9);
final ArrayNode roles = (ArrayNode) organization.get("Roles");
assertEquals(3, roles.size());
}
@Test
void testExpandEntitySetViaNonKeyField_FieldNotSelected() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/AdministrativeInformation/Created?$select=At&$expand=User");
helper.assertStatus(200);
final ObjectNode created = helper.getValue();
assertNotNull(created.get("User"));
}
@Test
void testExpandEntitySetViaNonKeyFieldNavigation2Hops() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/AdministrativeInformation/Created?$expand=User");
helper.assertStatus(200);
final ObjectNode created = helper.getValue();
@SuppressWarnings("unused")
final ObjectNode user = (ObjectNode) created.get("User");
}
@Test
void testExpandEntityViaComplexProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/Address?$expand=AdministrativeDivision");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
final ObjectNode created = (ObjectNode) organization.get("AdministrativeDivision");
assertEquals("USA", created.get("ParentDivisionCode").asText());
}
@Test
void testExpandEntitySetViaNonKeyFieldNavigation0Hops() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')?$expand=AdministrativeInformation/Created/User");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
final ObjectNode admin = (ObjectNode) organization.get("AdministrativeInformation");
final ObjectNode created = (ObjectNode) admin.get("Created");
assertNotNull(created.get("User"));
}
@Test
void testExpandEntitySetViaNonKeyFieldNavigation1Hop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/AdministrativeInformation?$expand=Created/User");
helper.assertStatus(200);
final ObjectNode admin = helper.getValue();
final ObjectNode created = (ObjectNode) admin.get("Created");
assertNotNull(created.get("User"));
}
@Test
void testExpandSingletonViaNonKeyFieldNavigation1Hop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CurrentUser/AdministrativeInformation?$expand=Created/User");
helper.assertStatus(200);
final ObjectNode admin = helper.getValue();
final ObjectNode created = (ObjectNode) admin.get("Created");
assertNotNull(created.get("User"));
}
@Test
void testNestedExpandNestedExpand2LevelsSelf() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE253',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent($expand=Children)");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ObjectNode parent = (ObjectNode) divisions.get("Parent");
assertNotNull(parent.get("Children"));
final ArrayNode children = (ArrayNode) parent.get("Children");
assertEquals(8, children.size());
assertEquals("NUTS3", children.get(0).get("CodeID").asText());
}
@Test
void testNestedExpandNestedExpand3LevelsSelf() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='33016',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($expand=Parent($expand=Parent))");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ObjectNode parent = (ObjectNode) divisions.get("Parent");
assertNotNull(parent.get("Parent"));
assertNotNull(parent.get("Parent").get("CodeID"));
assertEquals("NUTS3", parent.get("CodeID").asText());
final ObjectNode grandParent = (ObjectNode) parent.get("Parent");
assertNotNull(grandParent);
assertNotNull(grandParent.get("CodeID"));
assertEquals("NUTS2", grandParent.get("CodeID").asText());
final ObjectNode greatGrandParent = (ObjectNode) grandParent.get("Parent");
assertNotNull(greatGrandParent);
assertNotNull(greatGrandParent.get("CodeID"));
assertEquals("NUTS1", greatGrandParent.get("CodeID").asText());
}
@Test
void testNestedExpandNestedExpand3Only1PossibleLevelsSelf() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent($expand=Parent($expand=Parent))");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ObjectNode parent = (ObjectNode) divisions.get("Parent");
assertNotNull(parent.get("CodeID"));
assertEquals("NUTS1", parent.get("CodeID").asText());
}
@Test
void testNestedExpandNestedExpand2LevelsMixed() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/Address?$select=Country&$expand=AdministrativeDivision($expand=Parent)");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ObjectNode admin = (ObjectNode) divisions.get("AdministrativeDivision");
assertNotNull(admin);
final ObjectNode parent = (ObjectNode) admin.get("Parent");
assertEquals("3166-1", parent.get("CodeID").asText());
}
@Disabled("check how the result should look like")
@Test
void testExpandWithNavigationToEntity() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE253',CodeID='3',CodePublisher='NUTS')?$expand=Parent/Parent");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ObjectNode parent = (ObjectNode) divisions.get("Parent");
assertNotNull(parent.get("Parent").get("CodeID"));
assertEquals("1", parent.get("Parent").get("CodeID").asText());
}
@Disabled("Check with Olingo looks like OData does not support this")
@Test
void testExpandWithNavigationToProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE253',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent/CodeID");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ObjectNode parent = (ObjectNode) divisions.get("Parent");
assertNotNull(parent.get("CodeID"));
assertEquals("NUTS2", parent.get("CodeID").asText());
// TODO: Check how to create the response correctly
}
@Test
void testExpandAfterNavigationToEntity() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$filter=DivisionCode eq 'BE21'&$expand=Children($orderby=DivisionCode)");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ArrayNode children = (ArrayNode) divisions.get("value").get(0).get("Children");
assertNotNull(children);
assertEquals(3, children.size());
assertEquals("BE211", children.get(0).get("DivisionCode").asText());
assertEquals("BE212", children.get(1).get("DivisionCode").asText());
assertEquals("BE213", children.get(2).get("DivisionCode").asText());
}
@Test
void testExpandAfterNavigationToEntityWithTop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$filter=DivisionCode eq 'BE21'&$top=2&$expand=Children($orderby=DivisionCode)");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ArrayNode children = (ArrayNode) divisions.get("value").get(0).get("Children");
assertNotNull(children);
assertEquals(3, children.size());
assertEquals("BE211", children.get(0).get("DivisionCode").asText());
assertEquals("BE212", children.get(1).get("DivisionCode").asText());
assertEquals("BE213", children.get(2).get("DivisionCode").asText());
}
@Test
void testExpandViaNavigationToOneFails() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Parent/Children");
helper.assertStatus(400);
}
@Test
void testExpandWithOrderByDesc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode desc)");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ArrayNode children = (ArrayNode) divisions.get("Children");
assertEquals(5, children.size());
assertEquals("BE25", children.get(0).get("DivisionCode").asText());
}
@Test
void testExpandWithTopSkip2Level() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodeID eq 'NUTS1'&$top=4&$skip=1&$expand=Children($top=2;$expand=Children($top=1;$skip=1))&orderby=DivisionCode");
helper.assertStatus(200);
final ArrayNode grands = helper.getValues();
assertEquals(4, grands.size());
final ObjectNode grand = (ObjectNode) grands.get(1);
assertEquals("BE3", grand.get("DivisionCode").asText());
final ArrayNode parents = (ArrayNode) grand.get("Children");
assertEquals(2, parents.size());
final ObjectNode parent = (ObjectNode) parents.get(1);
assertEquals("BE32", parent.get("DivisionCode").asText());
final ArrayNode children = (ArrayNode) parent.get("Children");
assertEquals(1, children.size());
}
@Test
void testExpandWithOrderByAsc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode asc)");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ArrayNode children = (ArrayNode) divisions.get("Children");
assertEquals(5, children.size());
assertEquals("BE21", children.get(0).get("DivisionCode").asText());
}
@Test
void testExpandWithOrderByDescTop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$select=CodeID&$expand=Children($top=2;$orderby=DivisionCode desc)");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ArrayNode children = (ArrayNode) divisions.get("Children");
assertEquals(2, children.size());
assertEquals("BE25", children.get(0).get("DivisionCode").asText());
}
@Test
void testExpandWithOrderByDescTopSkip() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($top=2;$skip=2;$orderby=DivisionCode desc)");
helper.assertStatus(200);
final ObjectNode divisions = helper.getValue();
final ArrayNode children = (ArrayNode) divisions.get("Children");
assertEquals(2, children.size());
assertEquals("BE23", children.get(0).get("DivisionCode").asText());
}
@Test
void testExpandWithOrderByDescriptionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$select=ID&$expand=SupportedOrganizations($select=ID,LocationName;$orderby=LocationName desc)");
helper.assertStatus(200);
}
@Test
void testExpandWithOrderByToOneDescriptionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$expand=Roles($orderby=Organization/LocationName desc)");
helper.assertStatus(200);
}
@Test
void testExpandWithCount() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$count=true&$expand=Roles($count=true)");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
final ObjectNode organization = (ObjectNode) organizations.get(0);
assertNotNull(organization.get("Roles"));
final ArrayNode roles = (ArrayNode) organization.get("Roles");
assertNotNull(organization.get("Roles@odata.count"));
assertEquals(roles.size(), organization.get("Roles@odata.count").asInt());
}
@Test
void testExpandWithCount2Level() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"""
AdministrativeDivisions?$count=true\
&$expand=Children($count=true;$expand=Children($count=true))\
&$filter=CodeID eq 'NUTS1' and startswith(DivisionCode,'BE')""");
helper.assertStatus(200);
final ArrayNode grands = helper.getValues();
final ObjectNode grand = (ObjectNode) grands.get(1);
assertNotNull(grand.get("Children"));
final ArrayNode parents = (ArrayNode) grand.get("Children");
assertNotNull(grand.get("Children@odata.count"));
assertEquals(parents.size(), grand.get("Children@odata.count").asInt());
final ObjectNode parent = (ObjectNode) parents.get(2);
final ArrayNode children = (ArrayNode) parent.get("Children");
assertNotNull(children);
assertNotNull(parent.get("Children@odata.count"));
assertEquals(children.size(), parent.get("Children@odata.count").asInt());
}
@Test
void testExpandWithCountViaJoinTable() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"JoinSources(1)?$expand=OneToMany($count=true)");
helper.assertStatus(200);
final ObjectNode source = helper.getValue();
assertNotNull(source.get("OneToMany"));
final ArrayNode targets = (ArrayNode) source.get("OneToMany");
assertNotNull(source.get("OneToMany@odata.count"));
assertEquals(targets.size(), source.get("OneToMany@odata.count").asInt());
}
@Test
void testExpandWithCountWithOrderBy() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$count=true&$expand=Roles($count=true)&$orderby=Roles/$count desc");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
final ObjectNode organization = (ObjectNode) organizations.get(0);
assertNotNull(organization.get("Roles"));
final ArrayNode roles = (ArrayNode) organization.get("Roles");
assertNotNull(organization.get("Roles@odata.count"));
assertEquals(roles.size(), organization.get("Roles@odata.count").asInt());
}
@Test
void testExpandWithCountOrderBy() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$count=true&$expand=Children($count=true;$orderby=Children/$count desc,DivisionCode desc)&$filter=CodeID eq 'NUTS1' and startswith(DivisionCode,'BE')");
helper.assertStatus(200);
final ArrayNode parents = helper.getValues();
final ObjectNode parent = (ObjectNode) parents.get(1);
final ArrayNode children = (ArrayNode) parent.get("Children");
assertNotNull(children);
assertNotNull(parent.get("Children@odata.count"));
assertEquals(children.size(), parent.get("Children@odata.count").asInt());
final ObjectNode child = (ObjectNode) children.get(0);
assertEquals("BE25", child.get("DivisionCode").asText());
}
@Test
void testExpandWithCountPath() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('2')?$expand=Roles/$count");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertNotNull(organization.get("Roles@odata.count"));
assertEquals(2, organization.get("Roles@odata.count").asInt());
}
@Disabled("ODataJsonSerializer.writeExpandedNavigationProperty does not write a \"@odata.count\" for to 1 relations")
@Test
void testExpandOppositeDirectionWithCount() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')?$expand=Organization/$count");
helper.assertStatus(200);
final ObjectNode role = helper.getValue();
assertNotNull(role.get("Organization"));
assertNotNull(role.get("Organization@odata.count"));
assertEquals("1", role.get("Organization@odata.count").asText());
}
@Test
void testExpandWithCountAndTop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$count=true&$expand=Roles($count=true;$top=1)&$orderby=Roles/$count desc");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
final ObjectNode organization = (ObjectNode) organizations.get(0);
assertNotNull(organization.get("Roles"));
assertNotNull(organization.get("Roles@odata.count"));
assertEquals(3, organization.get("Roles@odata.count").asInt());
}
@Test
void testExpandWithOrderByDescTopSkipAndExternalOrderBy() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$count=true&$expand=Roles($orderby=RoleCategory desc)&$orderby=Roles/$count desc");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
final ObjectNode organization = (ObjectNode) organizations.get(0);
assertEquals("3", organization.get("ID").asText());
assertNotNull(organization.get("Roles"));
final ArrayNode roles = (ArrayNode) organization.get("Roles");
assertEquals(3, roles.size());
final ObjectNode firstRole = (ObjectNode) roles.get(0);
assertEquals("C", firstRole.get("RoleCategory").asText());
}
@Test
void testExpandWithFilter() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Children($filter=DivisionCode eq 'BE252')");
helper.assertStatus(200);
final ObjectNode division = helper.getValue();
assertEquals("BE25", division.get("DivisionCode").asText());
assertNotNull(division.get("Children"));
final ArrayNode children = (ArrayNode) division.get("Children");
assertEquals(1, children.size());
final ObjectNode firstChild = (ObjectNode) children.get(0);
assertEquals("BE252", firstChild.get("DivisionCode").asText());
}
@Test
void testFilterExpandWithFilter() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=DivisionCode eq 'BE25' and CodeID eq 'NUTS2'&$expand=Children($filter=DivisionCode eq 'BE252')");
helper.assertStatus(200);
final JsonNode value = helper.getValue().get("value");
assertNotNull(value.get(0));
final ObjectNode division = (ObjectNode) value.get(0);
assertEquals("BE25", division.get("DivisionCode").asText());
final ArrayNode children = (ArrayNode) division.get("Children");
assertEquals(1, children.size());
final ObjectNode firstChild = (ObjectNode) children.get(0);
assertEquals("BE252", firstChild.get("DivisionCode").asText());
}
@Test
void testFilterExpandWithFilterOnParentDescription() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$select=ID&$filter=LocationName eq 'Deutschland'&$expand=Roles&$orderby=ID asc");
helper.assertStatus(200);
final JsonNode value = helper.getValue().get("value");
assertNotNull(value.get(0));
final ArrayNode roles = (ArrayNode) value.get(0).get("Roles");
assertEquals(1, roles.size());
}
@Test
void testExpandCompleteEntitySet() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$expand=Roles&$orderby=ID");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
final ObjectNode organization = (ObjectNode) organizations.get(0);
assertEquals("1", organization.get("ID").asText());
assertNotNull(organization.get("Roles"));
final ArrayNode roles = (ArrayNode) organization.get("Roles");
assertEquals(1, roles.size());
final ObjectNode firstRole = (ObjectNode) roles.get(0);
assertEquals("A", firstRole.get("RoleCategory").asText());
}
@Test
void testExpandTwoNavigationPath() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE32',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent,Children");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertNotNull(organization.get("Parent"));
final ObjectNode parent = (ObjectNode) organization.get("Parent");
assertNotNull(parent.get("DivisionCode"));
final ArrayNode children = (ArrayNode) organization.get("Children");
assertEquals(7, children.size());
}
@Test
void testExpandAllNavigationPath() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE32',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=*");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertNotNull(organization.get("Parent"));
final ObjectNode parent = (ObjectNode) organization.get("Parent");
assertNotNull(parent.get("DivisionCode"));
final ArrayNode children = (ArrayNode) organization.get("Children");
assertEquals(7, children.size());
}
@Test
void testExpandLevel1() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='38025',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($levels=1)");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertNotNull(organization.get("Parent"));
final ObjectNode parent = (ObjectNode) organization.get("Parent");
assertNotNull(parent.get("DivisionCode"));
final TextNode divisionCode = (TextNode) parent.get("DivisionCode");
assertEquals("BE258", divisionCode.asText());
}
@Test
void testExpandLevel2() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='38025',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($levels=2)");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertFalse(organization.get("Parent") instanceof NullNode);
final ObjectNode parent = (ObjectNode) organization.get("Parent");
final TextNode parentDivisionCode = (TextNode) parent.get("DivisionCode");
assertEquals("BE258", parentDivisionCode.asText());
assertFalse(parent.get("Parent") instanceof NullNode);
final ObjectNode grandParent = (ObjectNode) parent.get("Parent");
assertNotNull(grandParent.get("DivisionCode"));
final TextNode grandparentDivisionCode = (TextNode) grandParent.get("DivisionCode");
assertEquals("BE25", grandparentDivisionCode.asText());
assertTrue(grandParent.get("Parent") == null || grandParent.get("Parent") instanceof NullNode);
}
@Test
void testExpandStarAndLevel2() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='38025',CodeID='LAU2',CodePublisher='Eurostat')?$expand=*($levels=2)");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertFalse(organization.get("Parent") instanceof NullNode);
final ObjectNode parent = (ObjectNode) organization.get("Parent");
final TextNode parentDivisionCode = (TextNode) parent.get("DivisionCode");
assertEquals("BE258", parentDivisionCode.asText());
assertFalse(parent.get("Parent") instanceof NullNode);
final ObjectNode grandParent = (ObjectNode) parent.get("Parent");
assertNotNull(grandParent.get("DivisionCode"));
final TextNode grandparentDivisionCode = (TextNode) grandParent.get("DivisionCode");
assertEquals("BE25", grandparentDivisionCode.asText());
assertTrue(grandParent.get("Parent") == null || grandParent.get("Parent") instanceof NullNode);
}
@Test
void testExpandStarAndLevel1() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE258',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=*($levels=1)");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertFalse(organization.get("Parent") instanceof NullNode);
final ObjectNode parent = (ObjectNode) organization.get("Parent");
final TextNode parentDivisionCode = (TextNode) parent.get("DivisionCode");
assertEquals("BE25", parentDivisionCode.asText());
assertTrue(parent.get("Parent") == null || parent.get("Parent") instanceof NullNode);
assertFalse(organization.get("Children") instanceof NullNode);
final ArrayNode children = (ArrayNode) organization.get("AllDescriptions");
assertTrue(children.size() > 0);
assertFalse(organization.get("AllDescriptions") instanceof NullNode);
final ArrayNode allDescriptions = (ArrayNode) organization.get("AllDescriptions");
assertTrue(allDescriptions.size() > 0);
}
@Disabled("Not implemented")
@Test
void testExpandLevelMax() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions(DivisionCode='BE241',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent($levels=max)");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
assertFalse(organization.get("Parent") instanceof NullNode);
final ObjectNode parent = (ObjectNode) organization.get("Parent");
final TextNode parentDivisionsCode = (TextNode) parent.get("DivisionCode");
assertEquals("BE24", parentDivisionsCode.asText());
assertFalse(parent.get("Parent") instanceof NullNode);
final ObjectNode grandParent = (ObjectNode) parent.get("Parent");
assertNotNull(grandParent.get("DivisionCode"));
final TextNode grandparentDivisionsCode = (TextNode) grandParent.get("DivisionCode");
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | true |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandSubCountQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandSubCountQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class JPAExpandSubCountQueryTest extends TestBase {
private JPAExpandSubCountQuery cut;
private OData odata;
private JPAEdmProvider edmProvider;
private JPAODataRequestContextAccess requestContext;
private JPAEntityType et;
private JPAAssociationPath association;
private List<JPANavigationPropertyInfo> hops;
private JPAServiceDocument sd;
@BeforeEach
void setup() throws ODataException {
odata = OData.newInstance();
edmProvider = mock(JPAEdmProvider.class);
requestContext = mock(JPAODataRequestContextAccess.class);
et = mock(JPAEntityType.class);
sd = mock(JPAServiceDocument.class);
association = mock(JPAAssociationPath.class);
hops = new ArrayList<>();
when(requestContext.getEntityManager()).thenReturn(emf.createEntityManager());
when(edmProvider.getServiceDocument()).thenReturn(sd);
when(requestContext.getEdmProvider()).thenReturn(edmProvider);
}
@Test
void testConvertCountResultCanHandleInteger() throws ODataException {
final List<Tuple> intermediateResult = new ArrayList<>();
final Tuple row = mock(Tuple.class);
when(row.get(JPAAbstractQuery.COUNT_COLUMN_NAME)).thenReturn(Integer.valueOf(5));
intermediateResult.add(row);
cut = new JPAExpandSubCountQuery(odata, requestContext, et, association, hops);
final Map<String, Long> act = cut.convertCountResult(intermediateResult);
assertNotNull(act);
assertEquals(1, act.size());
assertEquals(5L, act.get(""));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectWithGroupClause.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectWithGroupClause.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.criteria.Selection;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerWithGroups;
import com.sap.olingo.jpa.processor.core.util.SelectOptionDouble;
import com.sap.olingo.jpa.processor.core.util.TestGroupBase;
import com.sap.olingo.jpa.processor.core.util.UriInfoDouble;
class TestJPAQuerySelectWithGroupClause extends TestGroupBase {
@Test
void checkSelectAllWithoutGroupReturnsNotAssigned() throws ODataApplicationException {
fillJoinTable(root);
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("*"))).joinedPersistent(), root, Collections.emptyList());
assertContains(selectClause, "ID");
assertContainsNot(selectClause, "Country");
assertContainsNot(selectClause, "CommunicationData/LandlinePhoneNumber");
assertContainsNot(selectClause, "CreationDateTime");
}
@Test
void checkSelectAllWithOneGroupReturnsAlsoThose() throws ODataException {
root = emf.getCriteriaBuilder().createTupleQuery().from(BusinessPartnerWithGroups.class);
fillJoinTable(root);
final List<String> groups = new ArrayList<>();
groups.add("Person");
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("*"))).joinedPersistent(), root, groups);
assertContains(selectClause, "ID");
assertContains(selectClause, "Country");
assertContains(selectClause, "CommunicationData/LandlinePhoneNumber");
assertContainsNot(selectClause, "CreationDateTime");
}
@Test
void checkSelectAllWithTwoGroupReturnsAlsoThose() throws ODataException {
root = emf.getCriteriaBuilder().createTupleQuery().from(BusinessPartnerWithGroups.class);
fillJoinTable(root);
final List<String> groups = new ArrayList<>();
groups.add("Person");
groups.add("Company");
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("*"))).joinedPersistent(), root, groups);
assertContains(selectClause, "ID");
assertContains(selectClause, "Country");
assertContains(selectClause, "CommunicationData/LandlinePhoneNumber");
assertContains(selectClause, "CreationDateTime");
}
@Test
void checkSelectTwoWithOneGroupReturnsAll() throws ODataApplicationException {
root = emf.getCriteriaBuilder().createTupleQuery().from(BusinessPartnerWithGroups.class);
fillJoinTable(root);
final List<String> groups = new ArrayList<>();
groups.add("Person");
groups.add("Company");
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Type,CreationDateTime"))).joinedPersistent(), root, groups);
assertContains(selectClause, "ID");
assertContainsNot(selectClause, "Country");
assertContainsNot(selectClause, "CommunicationData/LandlinePhoneNumber");
assertContains(selectClause, "CreationDateTime");
}
@Test
void checkSelectTwoWithOneGroupReturnsOnlyID() throws ODataApplicationException {
root = emf.getCriteriaBuilder().createTupleQuery().from(BusinessPartnerWithGroups.class);
fillJoinTable(root);
final List<String> groups = new ArrayList<>();
groups.add("Test");
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Type,CreationDateTime"))).joinedPersistent(), root, groups);
assertContains(selectClause, "ID");
assertContainsNot(selectClause, "Country");
assertContainsNot(selectClause, "CommunicationData/LandlinePhoneNumber");
assertContainsNot(selectClause, "CreationDateTime");
}
@Test
void checkSelectTwoWithoutGroupReturnsOnlyID() throws ODataApplicationException {
root = emf.getCriteriaBuilder().createTupleQuery().from(BusinessPartnerWithGroups.class);
fillJoinTable(root);
final JPAODataGroupsProvider groups = new JPAODataGroupsProvider();
groups.addGroup("Test");
final List<Selection<?>> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(
new UriInfoDouble(new SelectOptionDouble("Type,CreationDateTime"))).joinedPersistent(), root, Collections
.emptyList());
assertContains(selectClause, "ID");
assertContainsNot(selectClause, "Country");
assertContainsNot(selectClause, "CommunicationData/LandlinePhoneNumber");
assertContainsNot(selectClause, "CreationDateTime");
}
private void assertContains(final List<Selection<?>> selectClause, final String alias) {
for (final Selection<?> selection : selectClause) {
if (selection.getAlias().equals(alias))
return;
}
fail(alias + " not found");
}
private void assertContainsNot(final List<Selection<?>> selectClause, final String alias) {
for (final Selection<?> selection : selectClause) {
if (selection.getAlias().equals(alias))
fail(alias + " was found, but was not expected");
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAOrderByBuilderTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAOrderByBuilderTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Order;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceCount;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.queryoption.OrderByItem;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.eclipse.persistence.internal.jpa.querydef.FunctionExpressionImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.properties.JPAOrderByPropertyFactory;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class JPAOrderByBuilderTest extends TestBase {
private JPAOrderByBuilder cut;
private Map<String, From<?, ?>> joinTables;
private UriInfoResource uriResource;
private TopOption top;
private SkipOption skip;
private OrderByOption orderBy;
private From<?, ?> adminTarget;
private From<?, ?> organizationTarget;
private CriteriaBuilder cb;
private JPAEntityType jpaAdminEntity;
private JPAEntityType jpaOrganizationEntity;
private List<String> groups;
private UriInfo uriInfo;
private List<JPAProcessorAttribute> orderByAttributes;
@BeforeEach
void setup() throws ODataException {
cb = emf.getCriteriaBuilder();
jpaAdminEntity = getHelper().getJPAEntityType(AdministrativeDivisionDescription.class);
adminTarget = cb.createQuery().from(getHelper().getEntityType(AdministrativeDivisionDescription.class));
jpaOrganizationEntity = getHelper().getJPAEntityType(Organization.class);
organizationTarget = cb.createQuery().from(getHelper().getEntityType(Organization.class));
groups = new ArrayList<>();
cut = new JPAOrderByBuilder(jpaAdminEntity, adminTarget, cb, groups);
top = mock(TopOption.class);
skip = mock(SkipOption.class);
orderBy = mock(OrderByOption.class);
uriResource = mock(UriInfoResource.class);
uriInfo = mock(UriInfo.class);
joinTables = new HashMap<>();
orderByAttributes = new ArrayList<>();
when(top.getValue()).thenReturn(5);
when(skip.getValue()).thenReturn(5);
}
@Test
void testNoTopSkipOrderByReturnsEmptyList() throws ODataException {
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriInfo);
assertEquals(0, act.size());
}
@Test
void testTopReturnsByPrimaryKey() throws ODataException {
when(uriInfo.getTopOption()).thenReturn(top);
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriInfo);
assertEquals(4, act.size());
assertEquals(4, act.stream()
.filter(Order::isAscending)
.toList().size());
assertOrder(act);
}
@Test
void testSkipReturnsByPrimaryKey() throws ODataException {
when(uriInfo.getSkipOption()).thenReturn(skip);
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriInfo);
assertEquals(4, act.size());
assertEquals(4, act.stream()
.filter(Order::isAscending)
.toList().size());
assertOrder(act);
}
@Test
void testTopSkipReturnsByPrimaryKey() throws ODataException {
when(uriInfo.getTopOption()).thenReturn(top);
when(uriInfo.getSkipOption()).thenReturn(skip);
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriInfo);
assertEquals(4, act.size());
assertEquals(4, act.stream()
.filter(Order::isAscending)
.toList().size());
assertOrder(act);
}
@Test
void testOrderByOneProperty() throws ODataApplicationException {
createOrderByItem("Name");
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriInfo);
assertEquals(1, act.size());
assertFalse(act.get(0).isAscending());
}
@Test
void testOrderByNavigationCountDefault() throws ODataException {
createCountOrderByItem(false);
cut = new JPAOrderByBuilder(jpaOrganizationEntity, organizationTarget, cb, groups);
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriInfo);
assertEquals(1, act.size());
assertTrue(act.get(0).isAscending());
assertEquals("COUNT", ((FunctionExpressionImpl<?>) act.get(0).getExpression()).getOperation());
}
@Test
void testOrderByNavigationCountDescending() throws ODataException {
createCountOrderByItem(true);
cut = new JPAOrderByBuilder(jpaOrganizationEntity, organizationTarget, cb, groups);
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriInfo);
assertEquals(1, act.size());
assertFalse(act.get(0).isAscending());
assertEquals("COUNT", ((FunctionExpressionImpl<?>) act.get(0).getExpression()).getOperation());
}
@Test
void testOrderByPropertyAndTop() throws ODataException {
createOrderByItem("DivisionCode");
when(top.getValue()).thenReturn(5);
when(uriResource.getOrderByOption()).thenReturn(orderBy);
when(uriResource.getTopOption()).thenReturn(top);
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriResource);
assertFalse(act.isEmpty());
assertEquals(String.class, act.get(0).getExpression().getJavaType());
assertEquals("DivisionCode", act.get(0).getExpression().getAlias());
assertEquals(4, act.size());
}
@Test
void testThrowExceptionOrderByTransientPrimitiveSimpleProperty() throws ODataException {
final JPAEntityType jpaEntity = getHelper().getJPAEntityType(Person.class);
final From<?, ?> target = cb.createQuery().from(getHelper().getEntityType(Person.class));
cut = new JPAOrderByBuilder(jpaEntity, target, cb, groups);
createOrderByItem("FullName", jpaEntity, target);
final ODataJPAQueryException act = assertThrows(ODataJPAQueryException.class,
() -> cut.createOrderByList(joinTables, orderByAttributes, uriInfo));
assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), act.getStatusCode());
}
@Test
void testOrderByPropertyAndPage() throws ODataException {
createOrderByItem("DivisionCode");
when(uriInfo.getTopOption()).thenReturn(top);
when(uriResource.getOrderByOption()).thenReturn(orderBy);
final List<Order> act = cut.createOrderByList(joinTables, orderByAttributes, uriInfo);
assertFalse(act.isEmpty());
assertEquals(String.class, act.get(0).getExpression().getJavaType());
assertEquals("DivisionCode", act.get(0).getExpression().getAlias());
assertEquals(4, act.size());
}
private List<UriResource> createOrderByClause(final Boolean isDescending) {
final OrderByItem item = mock(OrderByItem.class);
final Member expression = mock(Member.class);
final List<UriResource> pathParts = new ArrayList<>();
when(item.getExpression()).thenReturn(expression);
if (isDescending != null) {
when(item.isDescending()).thenReturn(isDescending);
}
when(expression.getResourcePath()).thenReturn(uriInfo);
when(uriInfo.getUriResourceParts()).thenReturn(pathParts);
when(uriResource.getOrderByOption()).thenReturn(orderBy);
when(orderBy.getOrders()).thenReturn(Collections.singletonList(item));
return pathParts;
}
private void createOrderByItem(final String externalName) {
createOrderByItem(externalName, jpaAdminEntity, adminTarget);
}
private void createOrderByItem(final String externalName, final JPAEntityType jpaEntity, final From<?, ?> target) {
final List<UriResource> pathParts = createOrderByClause(Boolean.TRUE);
final UriResourceProperty part = mock(UriResourcePrimitiveProperty.class);
when(part.getKind()).thenReturn(UriResourceKind.primitiveProperty);
pathParts.add(part);
createPrimitiveEdmProperty(part, externalName);
final var attribute = new JPAOrderByPropertyFactory().createProperty(orderBy.getOrders().get(0), jpaEntity,
Locale.ENGLISH);
attribute.setTarget(target, joinTables, cb);
orderByAttributes.add(attribute);
}
private void createCountOrderByItem(final boolean descending) {
final OrderByItem item = mock(OrderByItem.class);
final var navigation = mock(UriResourceNavigation.class);
final var count = mock(UriResourceCount.class);
final var edmNavigation = mock(EdmNavigationProperty.class);
final Member expression = mock(Member.class);
when(uriInfo.getUriResourceParts()).thenReturn(Arrays.asList(navigation, count));
when(navigation.getProperty()).thenReturn(edmNavigation);
when(edmNavigation.getName()).thenReturn("Roles");
when(count.getKind()).thenReturn(UriResourceKind.count);
when(item.isDescending()).thenReturn(descending);
when(item.getExpression()).thenReturn(expression);
when(expression.getResourcePath()).thenReturn(uriInfo);
final var attribute = new JPAOrderByPropertyFactory().createProperty(item, jpaOrganizationEntity, Locale.ENGLISH);
attribute.setTarget(organizationTarget, joinTables, cb);
orderByAttributes.add(attribute);
}
private void createPrimitiveEdmProperty(final UriResourceProperty primitivePart, final String name) {
final EdmProperty edmPrimitiveProperty = mock(EdmProperty.class);
when(primitivePart.getProperty()).thenReturn(edmPrimitiveProperty);
when(edmPrimitiveProperty.getName()).thenReturn(name);
}
private void assertOrder(final List<Order> act) {
assertEquals("CodePublisher", act.get(0).getExpression().getAlias());
assertEquals("CodeID", act.get(1).getExpression().getAlias());
assertEquals("DivisionCode", act.get(2).getExpression().getAlias());
assertEquals("Language", act.get(3).getExpression().getAlias());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestTopSkipCountOnDerby.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestTopSkipCountOnDerby.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.processor.core.database.JPADerbySqlPatternProvider;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
/**
* Some databases, like derby do not support LIMIT OFFSET and return an Integer on $count
* <p>
* <p>
* 2024-06-30
*/
class TestTopSkipCountOnDerby {
private static final String PUNIT_NAME = "com.sap.olingo.jpa";
private static EntityManagerFactory emf;
private static DataSource dataSource;
@BeforeAll
public static void setupClass() {
dataSource = DataSourceHelper.createDataSource(DataSourceHelper.DB_DERBY);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, dataSource);
}
@Test
void testTop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$top=10", new JPADerbySqlPatternProvider());
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = ((ArrayNode) collection.get("value"));
assertEquals(10, act.size());
assertEquals("Eurostat", act.get(0).get("CodePublisher").asText());
assertEquals("LAU2", act.get(0).get("CodeID").asText());
assertEquals("31003", act.get(0).get("DivisionCode").asText());
}
@Test
void testSkip() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$skip=5", new JPADerbySqlPatternProvider());
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = ((ArrayNode) collection.get("value"));
assertEquals(243, act.size());
assertEquals("Eurostat", act.get(0).get("CodePublisher").asText());
assertEquals("LAU2", act.get(0).get("CodeID").asText());
assertEquals("31022", act.get(0).get("DivisionCode").asText());
}
@Test
void testTopSkip() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$top=10&$skip=5", new JPADerbySqlPatternProvider());
helper.assertStatus(200);
}
@ParameterizedTest
@ValueSource(strings = {
"AdministrativeDivisions/$count",
"Persons?$expand=Roles/$count",
"Persons('97')/InhouseAddress/$count" })
void testCount(final String query) throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, query);
helper.assertStatus(200);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountForInQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountForInQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.server.api.ODataApplicationException;
import org.mockito.ArgumentCaptor;
import com.sap.olingo.jpa.processor.cb.ProcessorSubquery;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
class JPANavigationCountForInQueryTest extends JPANavigationCountQueryTest {
@Override
protected JPANavigationSubQuery createCut() throws ODataApplicationException {
return new JPANavigationCountForInQuery(odata, helper.sd, jpaEntityType, em, parent, from, association, Optional
.of(claimsProvider), Collections.emptyList());
}
@SuppressWarnings("unchecked")
@Override
protected Subquery<Comparable<?>> createSubQuery() {
return mock(ProcessorSubquery.class);
}
@Override
protected void assertAggregateClaims(final Path<Object> roleCategoryPath, final Path<Object> idPath,
final Path<Object> sourceIdPath, final List<Path<Comparable<?>>> paths) {
assertNotNull(cut);
verify(cb).equal(roleCategoryPath, "A");
assertContainsPath(paths, 1, "iD");
}
@SuppressWarnings("unchecked")
@Override
protected void assertMultipleJoinColumns(final Subquery<Comparable<?>> subQuery,
final List<Path<Comparable<?>>> paths) {
final ArgumentCaptor<List<Selection<?>>> selectionCaptor = ArgumentCaptor.forClass(List.class);
final ArgumentCaptor<List<Expression<?>>> groupByCaptor = ArgumentCaptor.forClass(List.class);
verify((ProcessorSubquery<Comparable<?>>) subQuery).multiselect(selectionCaptor.capture());
verify((ProcessorSubquery<Comparable<?>>) subQuery).groupBy(groupByCaptor.capture());
assertContainsPath(selectionCaptor.getValue(), 3, "codePublisher", "parentCodeID", "parentDivisionCode");
assertContainsPath(groupByCaptor.getValue(), 3, "codePublisher", "parentCodeID", "parentDivisionCode");
assertContainsPath(paths, 3, "codePublisher", "codeID", "divisionCode");
}
@Override
@SuppressWarnings("unchecked")
protected void assertOneJoinColumnsWithClaims(final Subquery<Comparable<?>> subQuery, final Predicate equalExpression,
final List<Path<Comparable<?>>> paths) {
final ArgumentCaptor<Expression<Comparable<?>>> selectionCaptor = ArgumentCaptor.forClass(Expression.class);
final ArgumentCaptor<List<Expression<?>>> groupByCaptor = ArgumentCaptor.forClass(List.class);
final ArgumentCaptor<Expression<Boolean>> restrictionCaptor = ArgumentCaptor.forClass(Expression.class);
verify(subQuery).select(selectionCaptor.capture());
verify(subQuery).groupBy(groupByCaptor.capture());
verify(subQuery).where(restrictionCaptor.capture());
assertEquals("businessPartnerID", selectionCaptor.getValue().getAlias());
assertContainsPath(groupByCaptor.getValue(), 1, "businessPartnerID");
assertEquals(equalExpression, restrictionCaptor.getValue());
assertContainsPath(paths, 1, "iD");
}
@Override
protected void assertLeftEarlyAccess() {
assertThrows(ODataJPAIllegalAccessException.class, () -> cut.getLeftPaths());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
class TestJPAQueryOrderByClause {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
public static final String[] enumPackages = { "com.sap.olingo.jpa.processor.core.testmodel" };
protected static EntityManagerFactory emf;
protected Map<String, List<String>> headers;
protected static JPAEdmNameBuilder nameBuilder;
protected static DataSource dataSource;
@BeforeAll
public static void setupClass() {
dataSource = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, dataSource);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
}
@Test
void testOrderByOneProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Name1");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals("Eighth Org.", orgs.get(0).get("Name1").asText());
assertEquals("Third Org.", orgs.get(9).get("Name1").asText());
}
@Test
void testOrderByOneComplexPropertyAsc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Address/Region");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals("US-CA", orgs.get(0).get("Address").get("Region").asText());
assertEquals("US-UT", orgs.get(9).get("Address").get("Region").asText());
}
@Test
void testOrderByOneComplexPropertyDeepAsc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$orderby=AdministrativeInformation/Created/By");
helper.assertStatus(200);
}
@Test
void testOrderByTwoPropertiesDescAsc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$orderby=Address/Region desc,Name1 asc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals("US-UT", orgs.get(0).get("Address").get("Region").asText());
assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText());
assertEquals("Third Org.", orgs.get(9).get("Name1").asText());
}
@Test
void testOrderByTwoPropertiesDescDesc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$orderby=Address/Region desc,Name1 desc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals("US-UT", orgs.get(0).get("Address").get("Region").asText());
assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText());
assertEquals("First Org.", orgs.get(9).get("Name1").asText());
}
@Test
void testOrderBy$CountDesc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Roles/$count desc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals("3", orgs.get(0).get("ID").asText());
assertEquals("2", orgs.get(1).get("ID").asText());
}
@Test
void testOrderBy$CountAndSelectAsc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$select=ID,Name1,Name2,Address/CountryName&$orderby=Roles/$count asc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals("3", orgs.get(9).get("ID").asText());
assertEquals("2", orgs.get(8).get("ID").asText());
}
@Test
void testCollectionOrderBy$CountAsc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps?$orderby=FirstLevel/SecondLevel/Comment/$count asc");
helper.assertStatus(200);
final ArrayNode deeps = helper.getValues();
assertEquals("506", deeps.get(0).get("ID").asText());
assertEquals("501", deeps.get(1).get("ID").asText());
assertEquals("502", deeps.get(2).get("ID").asText());
}
@Test
void testCollectionOrderBy$CountDesc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps?$orderby=FirstLevel/SecondLevel/Comment/$count desc");
helper.assertStatus(200);
final ArrayNode deeps = helper.getValues();
assertEquals("502", deeps.get(0).get("ID").asText());
assertEquals("501", deeps.get(1).get("ID").asText());
}
@Test
void testOrderBy$CountAsc() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$select=ID&$orderby=Roles/$count asc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals("3", orgs.get(9).get("ID").asText());
assertEquals("2", orgs.get(8).get("ID").asText());
}
@Test
void testOrderBy$CountDescComplexPropertyAcs() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$orderby=Roles/$count desc,Address/Region desc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals("3", orgs.get(0).get("ID").asText());
assertEquals("2", orgs.get(1).get("ID").asText());
assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText());
assertEquals("6", orgs.get(9).get("ID").asText());
}
@Test
void testOrderByAndFilter() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodeID eq 'NUTS' or CodeID eq '3166-1'&$orderby=CountryCode desc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(4, orgs.size());
assertEquals("USA", orgs.get(0).get("CountryCode").asText());
}
@Test
void testOrderByAndTopSkip() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AdministrativeDivisions?$filter=CodeID eq 'NUTS' or CodeID eq '3166-1'&$orderby=CountryCode desc&$top=1&$skip=2");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(1, orgs.size());
assertEquals("CHE", orgs.get(0).get("CountryCode").asText());
}
@Test
void testOrderByNavigationOneHop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('3')/Roles?$orderby=RoleCategory desc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(3, orgs.size());
assertEquals("C", orgs.get(0).get("RoleCategory").asText());
}
@Test
void testOrderByGroupedPropertyWithoutGroup() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerWithGroupss?$orderby=Country desc");
helper.assertStatus(403);
}
@Test
void testOrderByPropertyWithGroupsOneGroup() throws IOException, ODataException {
final JPAODataGroupsProvider groups = new JPAODataGroupsProvider();
groups.addGroup("Person");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerWithGroupss?$orderby=Country desc", groups);
helper.assertStatus(200);
}
@Test
void testOrderByGroupedComplexPropertyWithoutGroup() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerWithGroupss?$orderby=Address/Country desc");
helper.assertStatus(403);
}
@Test
void testOrderByGroupedComplexPropertyWithGroupsOneGroup() throws IOException, ODataException {
final JPAODataGroupsProvider groups = new JPAODataGroupsProvider();
groups.addGroup("Company");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerWithGroupss?$orderby=Address/Country desc", groups);
helper.assertStatus(200);
}
@Test
void testOrderByOnTransientPrimitiveSimpleProperty() throws IOException, ODataException {
final JPAODataGroupsProvider groups = new JPAODataGroupsProvider();
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$orderby=FullName", groups);
helper.assertStatus(400);
}
@Test
void testOrderByOnTransientSimpleComplexPartProperty() throws IOException, ODataException {
final JPAODataGroupsProvider groups = new JPAODataGroupsProvider();
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$select=ID&$orderby=Address/Street", groups);
helper.assertStatus(400);
}
@Test
void testOrderByOnTransientCollectionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps?$orderby=FirstLevel/TransientCollection/$count asc");
helper.assertStatus(400);
}
@Test
void testOrderByToOneProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"AssociationOneToOneSources?$orderby=ColumnTarget/Source asc");
helper.assertStatus(200);
}
@Test
void testOrderByToOnePropertyViaComplex() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons?$select=ID&$orderby=AdministrativeInformation/Created/User/LastName asc");
helper.assertStatus(200);
}
@Test
void testOrderByToOnePropertyWithCollectionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles?$expand=BusinessPartner($expand=Roles;$select=ID)&$orderby=BusinessPartner/Country asc");
helper.assertStatus(200);
}
@Test
void testOrderByToTwoPropertyWithCollectionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles?$orderby=BusinessPartner/Country asc,BusinessPartner/ID asc");
helper.assertStatus(200);
}
@Test
void testOrderByDescriptionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$select=ID&$orderby=LocationName asc");
helper.assertStatus(200);
final ArrayNode orgs = helper.getValues();
assertEquals(10, orgs.size());
assertEquals("10", orgs.get(0).get("ID").asText());
}
@Test
void testOrderByDescriptionViaToOneProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerRoles?$orderby=Organization/LocationName desc");
helper.assertStatus(200);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/UtilityTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/UtilityTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmElement;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmSingleton;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourceSingleton;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAUtilException;
import com.sap.olingo.jpa.processor.core.testmodel.CurrentUser;
import com.sap.olingo.jpa.processor.core.testmodel.Singleton;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
class UtilityTest extends TestBase {
private UriInfoResource uriInfo;
private List<UriResource> resourceParts;
@BeforeEach
void setUp() throws ODataException {
getHelper();
uriInfo = mock(UriInfoResource.class);
resourceParts = new ArrayList<>();
}
@Test
void testDetermineNavigationPathReturnsSingleton() throws ODataApplicationException {
final UriResourceSingleton resourcePart = mock(UriResourceSingleton.class);
final EdmType edmType = mock(EdmType.class);
when(resourcePart.getKind()).thenReturn(UriResourceKind.singleton);
when(resourcePart.getType()).thenReturn(edmType);
when(edmType.getNamespace()).thenReturn(PUNIT_NAME);
when(edmType.getName()).thenReturn(CurrentUser.class.getSimpleName());
resourceParts.add(resourcePart);
final List<JPANavigationPropertyInfo> act = Utility.determineNavigationPath(helper.sd, resourceParts, uriInfo);
assertNotNull(act);
assertEquals(1, act.size());
}
@Test
void testDetermineAssociationPathCreatesPathForSingleton() throws ODataApplicationException {
final StringBuilder associationName = new StringBuilder("Details");
final UriResourceSingleton source = mock(UriResourceSingleton.class);
final EdmEntityType singletonType = mock(EdmEntityType.class);
when(singletonType.getNamespace()).thenReturn(PUNIT_NAME);
when(singletonType.getName()).thenReturn(Singleton.class.getSimpleName());
when(source.getType()).thenReturn(singletonType);
final JPAAssociationPath act = Utility.determineAssociationPath(helper.sd, source, associationName);
assertNotNull(act);
}
@Test
void testDetermineAssociationThrowExceptionOnStartNull() throws ODataJPAModelException {
final JPAServiceDocument sd = mock(JPAServiceDocument.class);
final EdmType navigationStart = mock(EdmType.class);
when(sd.getEntity(navigationStart)).thenReturn(null);
assertThrows(ODataJPAUtilException.class, () -> Utility.determineAssociation(sd, navigationStart, new StringBuilder(
"Start")));
}
@Test
void testDetermineAssociationReThrowsException() throws ODataJPAModelException {
final JPAServiceDocument sd = mock(JPAServiceDocument.class);
final EdmType navigationStart = mock(EdmType.class);
when(sd.getEntity(navigationStart)).thenThrow(ODataJPAModelException.class);
assertThrows(ODataJPAUtilException.class, () -> Utility.determineAssociation(sd, navigationStart, new StringBuilder(
"Start")));
}
@Test
void testDetermineKeyPredicatesEntitySet() throws ODataApplicationException {
final UriResourceEntitySet es = mock(UriResourceEntitySet.class);
final UriParameter keyElement = mock(UriParameter.class);
final List<UriParameter> keys = Collections.singletonList(keyElement);
when(es.getKeyPredicates()).thenReturn(keys);
final List<UriParameter> act = Utility.determineKeyPredicates(es);
assertEquals(keys, act);
}
@Test
void testDetermineKeyPredicatesNavigation() throws ODataApplicationException {
final UriResourceNavigation navigation = mock(UriResourceNavigation.class);
final UriParameter keyElement = mock(UriParameter.class);
final List<UriParameter> keys = Collections.singletonList(keyElement);
when(navigation.getKeyPredicates()).thenReturn(keys);
final List<UriParameter> act = Utility.determineKeyPredicates(navigation);
assertEquals(keys, act);
}
@Test
void testDetermineKeySingleton() throws ODataApplicationException {
final UriResourceSingleton singleton = mock(UriResourceSingleton.class);
final List<UriParameter> act = Utility.determineKeyPredicates(singleton);
assertTrue(act.isEmpty());
}
@Test
void testDetermineModifyEntitySetAndKeysOnlyEntitySet() {
final EdmEntitySet es = mock(EdmEntitySet.class);
final UriResourceEntitySet resourceItem = createEntitySetResource(es);
final List<UriResource> resources = Arrays.asList(resourceItem);
final EdmBindingTargetInfo act = Utility.determineModifyEntitySetAndKeys(resources);
assertEquals(es, act.getEdmBindingTarget());
assertEquals("", act.getNavigationPath());
assertEquals(0, act.getKeyPredicates().size());
}
@Test
void testDetermineModifyEntitySetAndKeysOnlyEntitySetKey() {
final EdmEntitySet es = mock(EdmEntitySet.class);
final UriResourceEntitySet resourceItem = createEntitySetResource(es);
final UriParameter keyParameter = mock(UriParameter.class);
final List<UriParameter> keyParameters = Arrays.asList(keyParameter);
when(resourceItem.getKeyPredicates()).thenReturn(keyParameters);
final List<UriResource> resources = Arrays.asList(resourceItem);
final EdmBindingTargetInfo act = Utility.determineModifyEntitySetAndKeys(resources);
assertEquals(es, act.getEdmBindingTarget());
assertEquals("", act.getNavigationPath());
assertEquals(1, act.getKeyPredicates().size());
}
@Test
void testDetermineModifyEntitySetAndKeysPlusNavigation() {
final EdmEntitySet es = mock(EdmEntitySet.class);
final UriResourceEntitySet entitySet = createEntitySetResource(es);
final UriResourceNavigation navigation = createNavigationResource();
final List<UriResource> resources = Arrays.asList(entitySet, navigation);
final EdmBindingTargetInfo act = Utility.determineModifyEntitySetAndKeys(resources);
assertEquals(es, act.getEdmBindingTarget());
assertEquals("Navigation", act.getNavigationPath());
assertEquals(0, act.getKeyPredicates().size());
}
@Test
void testDetermineModifyEntitySetAndKeysPlusNavigationKey() {
final EdmEntitySet es = mock(EdmEntitySet.class);
final UriResourceEntitySet entitySet = createEntitySetResource(es);
final UriResourceNavigation navigation = createNavigationResource();
final List<UriResource> resources = Arrays.asList(entitySet, navigation);
final UriParameter keyParameter = mock(UriParameter.class);
final List<UriParameter> keyParameters = Arrays.asList(keyParameter);
when(navigation.getKeyPredicates()).thenReturn(keyParameters);
final EdmBindingTargetInfo act = Utility.determineModifyEntitySetAndKeys(resources);
assertEquals(es, act.getEdmBindingTarget());
assertEquals("", act.getNavigationPath());
assertEquals(1, act.getKeyPredicates().size());
}
@Test
void testDetermineModifyEntitySetAndKeysPlusNavigationKeyTarget() {
final EdmEntitySet es = mock(EdmEntitySet.class);
final UriResourceEntitySet entitySet = createEntitySetResource(es);
final UriResourceNavigation navigation = createNavigationResource();
final List<UriResource> resources = Arrays.asList(entitySet, navigation);
final UriParameter keyParameter = mock(UriParameter.class);
final List<UriParameter> keyParameters = Arrays.asList(keyParameter);
when(navigation.getKeyPredicates()).thenReturn(keyParameters);
final EdmEntitySet newTarget = mock(EdmEntitySet.class);
when(es.getRelatedBindingTarget("Navigation")).thenReturn(newTarget);
final EdmBindingTargetInfo act = Utility.determineModifyEntitySetAndKeys(resources);
assertEquals(newTarget, act.getEdmBindingTarget());
assertEquals("", act.getNavigationPath());
assertEquals(1, act.getKeyPredicates().size());
}
@Test
void testDetermineModifyEntitySetSingleton() {
final EdmSingleton single = mock(EdmSingleton.class);
final UriResourceSingleton resourceItem = createSingletonResource(single);
final List<UriResource> resources = Arrays.asList(resourceItem);
final EdmBindingTargetInfo act = Utility.determineModifyEntitySetAndKeys(resources);
assertEquals(single, act.getEdmBindingTarget());
assertEquals("", act.getNavigationPath());
assertEquals(0, act.getKeyPredicates().size());
}
@Test
void testDetermineModifyEntitySetSingletonPlusNavigation() {
final EdmSingleton single = mock(EdmSingleton.class);
final UriResourceSingleton resourceItem = createSingletonResource(single);
final UriResourceNavigation navigation = createNavigationResource();
final List<UriResource> resources = Arrays.asList(resourceItem, navigation);
final EdmBindingTargetInfo act = Utility.determineModifyEntitySetAndKeys(resources);
assertEquals(single, act.getEdmBindingTarget());
assertEquals("Navigation", act.getNavigationPath());
assertEquals(0, act.getKeyPredicates().size());
}
@Test
void testDetermineAssociationsNavigationPathAndStar() throws ODataException {
final TestHelper helper = getHelper();
final ExpandOption expandOption = mock(ExpandOption.class);
final ExpandItem expandItem = mock(ExpandItem.class);
when(expandItem.isStar()).thenReturn(Boolean.TRUE);
when(expandOption.getExpandItems()).thenReturn(Collections.singletonList(expandItem));
final EdmNavigationProperty user = createNavigationProperty("User");
final EdmComplexType created = createComplexType("Created", "User", user);
final EdmComplexType updated = createComplexType("Updated", "User", user);
final EdmComplexType administrativeInformation = createComplexType("AdministrativeInformation", new Property(
"Created", created), new Property("Updated", updated));
final EdmEntityType person = createEntityType("Person", new Property("AdministrativeInformation",
administrativeInformation));
final EdmEntitySet persons = createEntitySet("Persons", person);
final UriResourceEntitySet es = createEntitySetResource(persons);
final UriResourceComplexProperty property = createComplexPropertyResource("AdministrativeInformation");
when(es.getEntityType()).thenReturn(person);
when(property.getComplexType()).thenReturn(administrativeInformation);
resourceParts.add(es);
resourceParts.add(property);
final Map<JPAExpandItem, JPAAssociationPath> act = Utility.determineAssociations(helper.sd, resourceParts,
expandOption);
assertEquals(2, act.size());
}
@Test
void testDetermineAssociationsSelectOneProperty() throws ODataException {
final TestHelper helper = getHelper();
final JPAPath commentPath = mock(JPAPath.class);
final Set<JPAPath> selectOptions = new HashSet<>();
final UriResourceEntitySet es = createEntitySetResource("Organizations");
final JPACollectionAttribute pathLeaf = mock(JPACollectionAttribute.class);
final EdmEntityType edmType = mock(EdmEntityType.class);
when(commentPath.getLeaf()).thenReturn(pathLeaf);
when(commentPath.getPath()).thenReturn(Collections.singletonList(pathLeaf));
when(commentPath.getAlias()).thenReturn("Comment");
when(es.getType()).thenReturn(edmType);
when(edmType.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(edmType.getName()).thenReturn("Organization");
resourceParts.add(es);
selectOptions.add(commentPath);
final Map<JPAPath, JPAAssociationPath> act = Utility.determineAssociations(helper.sd, resourceParts,
selectOptions);
assertEquals(1, act.size());
assertNotNull(act.get(commentPath));
}
@Test
void testDetermineAssociationsUriPathSelectPath() throws ODataException {
final TestHelper helper = getHelper();
final Set<JPAPath> selectOptions = new HashSet<>();
final UriResourceEntitySet es = createEntitySetResource("CollectionDeeps");
final UriResourceComplexProperty cp = createComplexPropertyResource("FirstLevel");
final EdmEntityType edmType = mock(EdmEntityType.class);
final JPAAttribute pathParent = mock(JPAAttribute.class);
final JPAPath commentPath = mock(JPAPath.class);
final JPACollectionAttribute pathLeaf = mock(JPACollectionAttribute.class);
when(commentPath.getLeaf()).thenReturn(pathLeaf);
when(commentPath.getPath()).thenReturn(Arrays.asList(pathParent, pathLeaf));
when(commentPath.getAlias()).thenReturn("SecondLevel/Comment");
when(es.getType()).thenReturn(edmType);
when(edmType.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(edmType.getName()).thenReturn("CollectionDeep");
resourceParts.add(es);
resourceParts.add(cp);
selectOptions.add(commentPath);
final Map<JPAPath, JPAAssociationPath> act = Utility.determineAssociations(helper.sd, resourceParts,
selectOptions);
assertEquals(1, act.size());
assertNotNull(act.get(commentPath));
assertEquals("FirstLevel/SecondLevel/Comment", act.get(commentPath).getAlias());
}
private UriResourceNavigation createNavigationResource() {
final EdmNavigationProperty property = mock(EdmNavigationProperty.class);
final UriResourceNavigation navigation = mock(UriResourceNavigation.class);
when(navigation.getKind()).thenReturn(UriResourceKind.navigationProperty);
when(navigation.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("Navigation");
when(navigation.getKeyPredicates()).thenReturn(Collections.emptyList());
return navigation;
}
private UriResourceEntitySet createEntitySetResource(final String name) {
return createEntitySetResource(createEntitySet(name, null));
}
private UriResourceEntitySet createEntitySetResource(final EdmEntitySet es) {
final UriResourceEntitySet resourceItem = mock(UriResourceEntitySet.class);
when(resourceItem.getKind()).thenReturn(UriResourceKind.entitySet);
when(resourceItem.getEntitySet()).thenReturn(es);
when(resourceItem.getKeyPredicates()).thenReturn(Collections.emptyList());
return resourceItem;
}
private UriResourceSingleton createSingletonResource(final EdmSingleton es) {
final UriResourceSingleton resourceItem = mock(UriResourceSingleton.class);
when(resourceItem.getKind()).thenReturn(UriResourceKind.singleton);
when(resourceItem.getSingleton()).thenReturn(es);
return resourceItem;
}
private UriResourceComplexProperty createComplexPropertyResource(final String name) {
final EdmProperty property = mock(EdmProperty.class);
final EdmComplexType complexType = mock(EdmComplexType.class);
when(property.getName()).thenReturn(name);
when(complexType.getNamespace()).thenReturn(PUNIT_NAME);
when(complexType.getName()).thenReturn(name);
return createComplexPropertyResource(complexType, property);
}
private UriResourceComplexProperty createComplexPropertyResource(final EdmComplexType complexType,
final EdmProperty property) {
final UriResourceComplexProperty resourceItem = mock(UriResourceComplexProperty.class);
when(resourceItem.getKind()).thenReturn(UriResourceKind.complexProperty);
when(resourceItem.getProperty()).thenReturn(property);
when(resourceItem.getComplexType()).thenReturn(complexType);
return resourceItem;
}
private EdmNavigationProperty createNavigationProperty(final String name) {
final var entityType = mock(EdmEntityType.class);
final var keyProperty = mock(EdmKeyPropertyRef.class);
final var navigationProperty = mock(EdmNavigationProperty.class);
when(navigationProperty.getName()).thenReturn(name);
when(navigationProperty.getType()).thenReturn(entityType);
when(entityType.getKeyPropertyRefs()).thenReturn(Collections.singletonList(keyProperty));
return navigationProperty;
}
private EdmComplexType createComplexType(final String name, final String navigationName,
final EdmNavigationProperty navigationProperty) {
final var complexType = mock(EdmComplexType.class);
when(complexType.getName()).thenReturn(name);
when(complexType.getNavigationProperty(navigationName)).thenReturn(navigationProperty);
return complexType;
}
private EdmComplexType createComplexType(final String name, final Property... properties) {
final var complexType = mock(EdmComplexType.class);
when(complexType.getName()).thenReturn(name);
for (final var property : properties) {
final var edmProperty = mock(EdmElement.class);
when(complexType.getProperty(property.name)).thenReturn(edmProperty);
when(edmProperty.getType()).thenReturn(property.type);
}
return complexType;
}
private EdmEntityType createEntityType(final String name, final Property... properties) {
final var entityType = mock(EdmEntityType.class);
when(entityType.getName()).thenReturn(name);
when(entityType.getNamespace()).thenReturn(PUNIT_NAME);
for (final var property : properties) {
final var edmProperty = mock(EdmElement.class);
when(entityType.getProperty(property.name)).thenReturn(edmProperty);
when(edmProperty.getType()).thenReturn(property.type);
}
return entityType;
}
private EdmEntitySet createEntitySet(final String name, final EdmEntityType et) {
final EdmEntitySet es = mock(EdmEntitySet.class);
when(es.getName()).thenReturn(name);
when(es.getEntityType()).thenReturn(et);
return es;
}
private static record Property(String name, EdmType type) {
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
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 java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Predicate.BooleanOperator;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.eclipse.persistence.internal.jpa.querydef.CompoundExpressionImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataApiVersionAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.testmodel.DeepProtectedExample;
import com.sap.olingo.jpa.processor.core.util.Assertions;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.JPAEntityTypeDouble;
import com.sap.olingo.jpa.processor.core.util.TestQueryBase;
class TestJPAQueryWithProtection extends TestQueryBase {
private JPAODataSessionContextAccess contextSpy;
private JPAServiceDocument sdSpy;
private EdmType odataType;
private List<JPAAttribute> attributes;
private Set<String> claimNames;
private List<String> pathList;
private JPAEntityType etSpy;
private List<JPAProtectionInfo> protections;
private CriteriaBuilder cbSpy;
private JPARequestParameterMap parameter;
@Override
@BeforeEach
public void setup() throws ODataException, ODataJPAIllegalAccessException {
super.setup();
final var version = context.getApiVersion(JPAODataApiVersionAccess.DEFAULT_VERSION);
final var versionSpy = spy(version);
contextSpy = spy(context);
final JPAEdmProvider providerSpy = spy(version.getEdmProvider());
sdSpy = spy(version.getEdmProvider().getServiceDocument());
when(contextSpy.getApiVersion(JPAODataApiVersionAccess.DEFAULT_VERSION)).thenReturn(versionSpy);
when(versionSpy.getEdmProvider()).thenReturn(providerSpy);
when(providerSpy.getServiceDocument()).thenReturn(sdSpy);
final EntityManager emSpy = spy(emf.createEntityManager());
parameter = mock(JPARequestParameterMap.class);
cbSpy = spy(emSpy.getCriteriaBuilder());
when(emSpy.getCriteriaBuilder()).thenReturn(cbSpy);
when(externalContext.getEntityManager()).thenReturn(emSpy);
when(externalContext.getRequestParameter()).thenReturn(parameter);
}
@Test
void testRestrictOnePropertyOneValue() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Willi"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID,Name1,Country", claims);
helper.assertStatus(200);
final ArrayNode bupa = helper.getValues();
assertEquals(3, bupa.size());
}
@ParameterizedTest
@ValueSource(strings = { "Wil*", "Wi%i", "Wil+i", "Will_", "Wi*i", "_illi" })
void testRestrictOnePropertyOneValueWithWildcard(final String minValue) throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>(minValue));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID,Name1,Country", claims);
helper.assertStatus(200);
final ArrayNode bupa = helper.getValues();
assertEquals(3, bupa.size());
}
@Test
void testRestrictOnePropertyTwoValues() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Willi"));
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID,Name1,Country", claims);
helper.assertStatus(200);
final ArrayNode bupa = helper.getValues();
assertEquals(13, bupa.size());
}
@ParameterizedTest
@CsvSource({
"200, 'Willi;Marvin', 16",
"200, 'Willi', 3", })
void testRestrictOnePropertyCount(final int statusCodeValue, final String claimEntries,
final int noResults) throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
final String[] claimEntriesList = claimEntries.split(";");
for (final String claimEntry : claimEntriesList) {
claims.add("UserId", new JPAClaimsPair<>(claimEntry));
}
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds/$count", claims);
helper.assertStatus(statusCodeValue);
final ValueNode act = helper.getSingleValue();
assertEquals(noResults, act.asInt());
}
@Test
void testRestrictNavigationResult() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
claims.add("RoleCategory", new JPAClaimsPair<>("A", "B"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds('3')/RolesProtected", claims);
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(2, act.size());
}
@Test
void testRestrictExpandResult() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
claims.add("RoleCategory", new JPAClaimsPair<>("A", "B"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$filter=ID eq '3'&$expand=RolesProtected", claims);
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(1, act.size());
final ArrayNode actExpand = (ArrayNode) act.get(0).get("RolesProtected");
assertEquals(2, actExpand.size());
}
@Tag(Assertions.CB_ONLY_TEST)
@Test
void testRestrictExpandResultWithTop() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
claims.add("RoleCategory", new JPAClaimsPair<>("A", "B"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$filter=ID eq '3'&$expand=RolesProtected($top=1)", claims);
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(1, act.size());
final ArrayNode actExpand = (ArrayNode) act.get(0).get("RolesProtected");
assertEquals(1, actExpand.size());
}
@Test
void testThrowsUnauthorizedOnMissingClaimForRestrictExpandResult() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$filter=ID eq '3'&$expand=RolesProtected", claims);
helper.assertStatus(403);
}
@ParameterizedTest
@CsvSource({
"200, 'Willi;Marvin', 16",
"200, 'Willi', 3", })
void testRestrictOnePropertyInlineCount(final int statusCodeValue, final String claimEntries,
final int noResults) throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
final String[] claimEntriesList = claimEntries.split(";");
for (final String claimEntry : claimEntriesList) {
claims.add("UserId", new JPAClaimsPair<>(claimEntry));
}
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$count=true", claims);
helper.assertStatus(statusCodeValue);
final ValueNode act = helper.getSingleValue("@odata.count");
assertEquals(noResults, act.asInt());
}
@Test
void testRestrictOnePropertyNoProvider() throws IOException, ODataException {
final JPAODataClaimsProvider claims = null;
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID,Name1,Country", claims);
helper.assertStatus(403);
}
@Test
void testRestrictOnePropertyNoValue() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID,Name1,Country", claims);
helper.assertStatus(403);
}
@Test
void testRestrictOnePropertyBetweenValues() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin", "Willi"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds?$select=ID,Name1,Country", claims);
helper.assertStatus(200);
final ArrayNode bupa = helper.getValues();
assertEquals(13, bupa.size());
}
@ParameterizedTest
@CsvSource({
"200, '1', 'Max'",
"200, '2', 'Urs'",
"200, '7', ''",
})
void testRestrictOnePropertyDeep(final int statusCodeValue, final String building, final String firstName)
throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("Creator", new JPAClaimsPair<>("*"));
claims.add("Updator", new JPAClaimsPair<>("*"));
claims.add("BuildingNumber", new JPAClaimsPair<>(building));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"PersonProtecteds?$select=ID,FirstName", claims);
helper.assertStatus(statusCodeValue);
final ArrayNode persons = helper.getValues();
if (!firstName.isEmpty()) {
assertEquals(1, persons.size());
assertEquals(firstName, persons.get(0).get("FirstName").asText());
} else
assertEquals(0, persons.size());
}
@Test
void testRestrictOnePropertyOneValueWithNavigationToRoles() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Willi"));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerProtecteds('99')/Roles", claims);
helper.assertStatus(200);
final ArrayNode bupa = helper.getValues();
assertEquals(2, bupa.size());
}
@Test
void testRestrictComplexOnePropertyOneValue() throws ODataException, JPANoSelectionException {
prepareTest();
prepareComplexAttributeCreateUser("UserId");
claimNames.add("UserId");
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath("UserId");
attributes.add(aSpy);
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
assertEqual(act);
}
@ParameterizedTest
@ValueSource(strings = { "Mar*", "Mar%", "Mar+", "Mar_" })
void testRestrictComplexOnePropertyOneValueWildcardTrue(final String minValue) throws ODataException,
JPANoSelectionException {
prepareTest();
prepareComplexAttributeUser("UserId", "AdministrativeInformation/Created/By", "created", true);
claimNames.add("UserId");
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>(minValue));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath("UserId");
attributes.add(aSpy);
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
assertLike(act);
}
@Test
void testRestrictComplexOnePropertyUpperLowerValues() throws ODataException, JPANoSelectionException {
final String claimName = "UserId";
prepareTest();
prepareComplexAttributeCreateUser(claimName);
claimNames.add(claimName);
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add(claimName, new JPAClaimsPair<>("Marvin", "Willi"));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath("UserId");
attributes.add(aSpy);
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
assertBetween(act);
}
@Test
void testRestrictComplexOnePropertyUpperLowerValuesWildcardTrue() throws ODataException,
JPANoSelectionException {
final String claimName = "UserId";
prepareTest();
prepareComplexAttributeUser(claimName, "AdministrativeInformation/Created/By", "created", true);
claimNames.add(claimName);
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add(claimName, new JPAClaimsPair<>("Marv*", "Willi"));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath("UserId");
attributes.add(aSpy);
assertThrows(ODataJPAQueryException.class, () -> cut.createProtectionWhere(Optional.of(
claims)));
}
@Test
void testRestrictComplexOnePropertyTwoValues() throws ODataException, JPANoSelectionException {
final String claimName = "UserId";
prepareTest();
prepareComplexAttributeCreateUser(claimName);
claimNames.add(claimName);
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add(claimName, new JPAClaimsPair<>("Marvin"));
claims.add(claimName, new JPAClaimsPair<>("Willi"));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath(claimName);
attributes.add(aSpy);
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
assertEquals(BooleanOperator.OR, ((CompoundExpressionImpl) act).getOperator());
for (final Expression<?> part : ((CompoundExpressionImpl) act).getChildExpressions())
assertEqual(part);
}
@Test
void testRestrictComplexOnePropertyOneValuesDate() throws ODataException, JPANoSelectionException {
final String claimName = "CreationDate";
prepareTest();
prepareComplexAttributeDate(claimName);
claimNames.add(claimName);
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add(claimName, new JPAClaimsPair<>(Date.valueOf("2010-01-01")));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath(claimName);
attributes.add(aSpy);
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
assertEqual(act);
}
@Test
void testRestrictComplexOnePropertyUpperLowerValuesDate() throws ODataException, JPANoSelectionException {
final String claimName = "CreationDate";
prepareTest();
prepareComplexAttributeDate(claimName);
claimNames.add(claimName);
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add(claimName, new JPAClaimsPair<>(Date.valueOf("2010-01-01"), Date.valueOf("9999-12-30")));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath(claimName);
attributes.add(aSpy);
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
assertBetween(act);
}
@Test
void testRestrictComplexTwoPropertyOneValuesOperatorAND() throws ODataException, JPANoSelectionException {
final String claimName = "UserId";
prepareTest();
prepareComplexAttributeCreateUser(claimName);
prepareComplexAttributeUpdateUser(claimName);
claimNames.add(claimName);
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add(claimName, new JPAClaimsPair<>("Marvin"));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath(claimName);
attributes.add(aSpy);
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
verify(cbSpy).and(any(), any());
for (final Expression<?> part : ((CompoundExpressionImpl) act).getChildExpressions())
assertEqual(part);
}
@Test
void testRestrictTwoPropertiesOneValuesOperatorAND() throws ODataException, JPANoSelectionException {
final String claimName = "UserId";
prepareTest();
prepareComplexAttributeCreateUser(claimName);
prepareComplexAttributeUpdateUser(claimName);
claimNames.add(claimName);
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Marvin"));
final JPAAttribute aSpy = spy(etSpy.getAttribute("administrativeInformation").get());
doReturn(true).when(aSpy).hasProtection();
doReturn(claimNames).when(aSpy).getProtectionClaimNames();
doReturn(pathList).when(aSpy).getProtectionPath(claimName);
attributes.add(aSpy);
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
verify(cbSpy).and(any(), any());
for (final Expression<?> part : ((Predicate) act).getExpressions())
assertEqual(part);
}
@Test
void testAllowAllOnNonStringProperties() throws ODataException, JPANoSelectionException {
prepareTestDeepProtected();
when(etSpy.getProtections()).thenCallRealMethod();
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("BuildingNumber", new JPAClaimsPair<>("DEV"));
claims.add("Floor", new JPAClaimsPair<>(Short.valueOf("12")));
claims.add("RoomNumber", new JPAClaimsPair<>("*"));
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
assertNotNull(act);
assertEquals(2, ((Predicate) act).getExpressions().size());
verify(cbSpy).and(any(), any());
}
@Test
void testAllowAllOnNonStringPropertiesAlsoDouble() throws ODataException, JPANoSelectionException {
prepareTestDeepProtected();
when(etSpy.getProtections()).thenCallRealMethod();
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("BuildingNumber", new JPAClaimsPair<>("DEV"));
claims.add("Floor", new JPAClaimsPair<>(Short.valueOf("12")));
claims.add("RoomNumber", new JPAClaimsPair<>("*"));
claims.add("RoomNumber", new JPAClaimsPair<>(1, 10));
cut.createProtectionWhere(Optional.of(claims));
verify(cbSpy).and(any(), any());
}
@Test
void testAllowAllOnMultipleClaims() throws ODataException, JPANoSelectionException {
prepareTestDeepProtected();
when(etSpy.getProtections()).thenCallRealMethod();
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("BuildingNumber", new JPAClaimsPair<>(JPAClaimsPair.ALL));
claims.add("Floor", new JPAClaimsPair<>(Short.valueOf("12")));
claims.add("RoomNumber", new JPAClaimsPair<>(JPAClaimsPair.ALL));
final Expression<Boolean> act = cut.createProtectionWhere(Optional.of(claims));
assertNotNull(act);
verify(cbSpy, times(0)).and(any(), any());
}
private void assertBetween(final Expression<Boolean> act) {
assertExpression(act, "between", 3);
}
private void assertEqual(final Expression<?> act) {
assertExpression(act, "equal", 2);
}
private void assertLike(final Expression<?> act) {
assertExpression(act, "like", 2);
}
private void assertExpression(final Expression<?> act, final String operator, final int size) {
assertNotNull(act);
final List<Expression<?>> actChildren = ((CompoundExpressionImpl) act).getChildExpressions();
assertEquals(size, actChildren.size());
assertEquals(operator, ((CompoundExpressionImpl) act).getOperation());
assertEquals("Path", actChildren.get(0).getClass().getInterfaces()[0].getSimpleName());
}
private void prepareComplexAttributeUser(final String claimName, final String pathName,
final String intermediateElement) throws ODataJPAModelException {
prepareComplexAttributeUser(claimName, pathName, intermediateElement, false);
}
private void prepareComplexAttributeUser(final String claimName, final String pathName,
final String intermediateElement, final boolean wildcardSupported) throws ODataJPAModelException {
final JPAProtectionInfo protection = mock(JPAProtectionInfo.class);
protections.add(protection);
final String path = pathName;
pathList.add(path);
final JPAPath jpaPath = mock(JPAPath.class);
final JPAElement adminAttribute = mock(JPAElement.class);
final JPAElement complexAttribute = mock(JPAElement.class);
final JPAAttribute simpleAttribute = mock(JPAAttribute.class);
final List<JPAElement> pathElements = Arrays.asList(adminAttribute, complexAttribute, simpleAttribute);
doReturn(pathElements).when(jpaPath).getPath();
doReturn("administrativeInformation").when(adminAttribute).getInternalName();
doReturn(intermediateElement).when(complexAttribute).getInternalName();
doReturn("by").when(simpleAttribute).getInternalName();
doReturn(String.class).when(simpleAttribute).getType();
doReturn(simpleAttribute).when(jpaPath).getLeaf();
doReturn(jpaPath).when(etSpy).getPath(path);
doReturn(simpleAttribute).when(protection).getAttribute();
doReturn(jpaPath).when(protection).getPath();
doReturn(claimName).when(protection).getClaimName();
doReturn(wildcardSupported).when(protection).supportsWildcards();
}
private void prepareComplexAttributeCreateUser(final String claimName) throws ODataJPAModelException {
prepareComplexAttributeUser(claimName, "AdministrativeInformation/Created/By", "created");
}
private void prepareComplexAttributeUpdateUser(final String claimName) throws ODataJPAModelException {
prepareComplexAttributeUser(claimName, "AdministrativeInformation/Updated/By", "updated");
}
private void prepareComplexAttributeDate(final String claimName) throws ODataJPAModelException {
final JPAProtectionInfo protection = mock(JPAProtectionInfo.class);
protections.add(protection);
final String path = "AdministrativeInformation/Created/At";
pathList.add(path);
final JPAPath jpaPath = mock(JPAPath.class);
final JPAElement adminAttribute = mock(JPAElement.class);
final JPAElement complexAttribute = mock(JPAElement.class);
final JPAAttribute simpleAttribute = mock(JPAAttribute.class);
final List<JPAElement> pathElements = Arrays.asList(adminAttribute, complexAttribute, simpleAttribute);
doReturn(pathElements).when(jpaPath).getPath();
doReturn("administrativeInformation").when(adminAttribute).getInternalName();
doReturn("created").when(complexAttribute).getInternalName();
doReturn("at").when(simpleAttribute).getInternalName();
doReturn(Date.class).when(simpleAttribute).getType();
doReturn(simpleAttribute).when(jpaPath).getLeaf();
doReturn(jpaPath).when(etSpy).getPath(path);
doReturn(simpleAttribute).when(protection).getAttribute();
doReturn(jpaPath).when(protection).getPath();
doReturn(claimName).when(protection).getClaimName();
}
private void prepareTest() throws ODataException, JPANoSelectionException {
buildUriInfo("BusinessPartnerProtecteds", "BusinessPartnerProtected");
odataType = ((UriResourceEntitySet) uriInfo.getUriResourceParts().get(0)).getType();
attributes = new ArrayList<>();
claimNames = new HashSet<>();
pathList = new ArrayList<>();
protections = new ArrayList<>();
etSpy = spy(new JPAEntityTypeDouble(sdSpy.getEntity("BusinessPartnerProtecteds")));
doReturn(attributes).when(etSpy).getAttributes();
doReturn(protections).when(etSpy).getProtections();
doReturn(etSpy).when(sdSpy).getEntity("BusinessPartnerProtecteds");
doReturn(etSpy).when(sdSpy).getEntity(odataType);
final JPAODataInternalRequestContext requestContext = new JPAODataInternalRequestContext(externalContext,
contextSpy, odata);
try {
requestContext.setUriInfo(uriInfo);
} catch (final ODataJPAIllegalAccessException e) {
fail();
}
cut = new JPAJoinQuery(null, requestContext);
cut.createFromClause(new ArrayList<>(1), new ArrayList<>(), cut.cq, null);
}
private void prepareTestDeepProtected() throws ODataException, JPANoSelectionException {
buildUriInfo("ProtectionExamples", "ProtectionExample");
odataType = ((UriResourceEntitySet) uriInfo.getUriResourceParts().get(0)).getType();
attributes = new ArrayList<>();
claimNames = new HashSet<>();
pathList = new ArrayList<>();
protections = new ArrayList<>();
etSpy = spy(new JPAEntityTypeDouble(sdSpy.getEntity(DeepProtectedExample.class)));
doReturn(attributes).when(etSpy).getAttributes();
doReturn(protections).when(etSpy).getProtections();
doReturn(etSpy).when(sdSpy).getEntity("ProtectionExamples");
doReturn(etSpy).when(sdSpy).getEntity(odataType);
doReturn(null).when(etSpy).getAssociation("");
final JPAODataInternalRequestContext requestContext = new JPAODataInternalRequestContext(externalContext,
contextSpy, odata);
try {
requestContext.setUriInfo(uriInfo);
} catch (final ODataJPAIllegalAccessException e) {
fail();
}
cut = new JPAJoinQuery(null, requestContext);
cut.createFromClause(new ArrayList<>(1), new ArrayList<>(), cut.cq, null);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQueryCollection extends TestBase {
@Test
void testSelectOneSimpleCollectionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('1')?$select=Comment");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
final ArrayNode comment = (ArrayNode) organization.get("Comment");
assertEquals(2, comment.size());
}
@Test
void testSelectOneComplexCollectionProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons('99')?$select=InhouseAddress");
helper.assertStatus(200);
final ObjectNode organization = helper.getValue();
final ArrayNode address = (ArrayNode) organization.get("InhouseAddress");
assertEquals(2, address.size());
}
@Test
void testSelectPropertyAndCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$select=ID,Comment&orderby=ID");
helper.assertStatus(200);
final ArrayNode organizations = helper.getValues();
final ObjectNode organization = (ObjectNode) organizations.get(0);
assertNotNull(organization.get("ID"));
final ArrayNode comment = (ArrayNode) organization.get("Comment");
assertEquals(2, comment.size());
}
// @Ignore // See https://issues.apache.org/jira/browse/OLINGO-1231
@Test
void testSelectPropertyOfCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons('99')/InhouseAddress?$select=Building");
helper.assertStatus(200);
final ArrayNode buildings = helper.getValues();
assertEquals(2, buildings.size());
final ObjectNode building = (ObjectNode) buildings.get(0);
final TextNode number = (TextNode) building.get("Building");
assertNotNull(number);
}
@Test
void testSelectAllWithComplexCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons('99')?$select=*");
helper.assertStatus(200);
final ObjectNode person = helper.getValue();
final ArrayNode comment = (ArrayNode) person.get("InhouseAddress");
assertEquals(2, comment.size());
}
@Test
void testSelectAllWithPrimitiveCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('1')?$select=*");
helper.assertStatus(200);
final ObjectNode person = helper.getValue();
final ArrayNode comment = (ArrayNode) person.get("Comment");
assertEquals(2, comment.size());
}
@Test
void testSelectWithNestedComplexCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Collections('503')?$select=Nested");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode nested = (ArrayNode) collection.get("Nested");
assertEquals(1, nested.size());
final ObjectNode n = (ObjectNode) nested.get(0);
assertEquals(1L, n.get("Number").asLong());
assertFalse(n.get("Inner") instanceof NullNode);
assertEquals(6L, n.get("Inner").get("Figure3").asLong());
}
@Test
void testSelectComplexContainingCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Collections('502')?$select=Complex");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ObjectNode complex = (ObjectNode) collection.get("Complex");
assertEquals(32L, complex.get("Number").asLong());
assertFalse(complex.get("Address") instanceof NullNode);
assertEquals(2, complex.get("Address").size());
for (int i = 0; i < complex.get("Address").size(); i++) {
final ObjectNode address = (ObjectNode) complex.get("Address").get(i);
if (address.get("Building").asText().equals("1")) {
assertEquals("DEV", address.get("TaskID").asText());
return;
}
}
fail("Task not found");
}
@Test
void testSelectComplexContainingTwoCollections() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Collections('501')?$select=Complex");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ObjectNode complex = (ObjectNode) collection.get("Complex");
assertEquals(-1L, complex.get("Number").asLong());
assertFalse(complex.get("Address") instanceof NullNode);
assertEquals(1, complex.get("Address").size());
assertEquals("MAIN", complex.get("Address").get(0).get("TaskID").asText());
assertFalse(complex.get("Comment") instanceof NullNode);
assertEquals(1, complex.get("Comment").size());
assertEquals("This is another test", complex.get("Comment").get(0).asText());
}
@Test
void testSelectAllWithComplexContainingCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Collections('502')");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ObjectNode complex = (ObjectNode) collection.get("Complex");
assertEquals(32L, complex.get("Number").asLong());
assertFalse(complex.get("Address") instanceof NullNode);
assertEquals(2, complex.get("Address").size());
for (int i = 0; i < complex.get("Address").size(); i++) {
final ObjectNode address = (ObjectNode) complex.get("Address").get(i);
if (address.get("Building").asText().equals("1")) {
assertEquals("DEV", address.get("TaskID").asText());
return;
}
}
fail("Task not found");
}
@Test
void testSelectAllDeepComplexContainingCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "CollectionDeeps('501')");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ObjectNode complex = (ObjectNode) collection.get("FirstLevel");
assertEquals(1, complex.get("LevelID").asInt());
assertFalse(complex.get("SecondLevel") instanceof NullNode);
final ObjectNode second = (ObjectNode) complex.get("SecondLevel");
final ArrayNode address = (ArrayNode) second.get("Address");
assertEquals(32, address.get(0).get("RoomNumber").asInt());
}
@Test
void testSelectOnlyOneCollectionDeepComplex() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('502')?$select=FirstLevel/SecondLevel/Comment");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final TextNode actId = (TextNode) collection.get("ID");
assertEquals("502", actId.asText());
final ObjectNode complex = (ObjectNode) collection.get("FirstLevel");
assertFalse(complex.get("SecondLevel") instanceof NullNode);
final ObjectNode second = (ObjectNode) complex.get("SecondLevel");
final ArrayNode comment = (ArrayNode) second.get("Comment");
assertEquals(2, comment.size());
}
@Test
void testSelectTwoCollectionDeepComplex() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('502')?$select=FirstLevel/SecondLevel/Comment,FirstLevel/SecondLevel/Address");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final TextNode actId = (TextNode) collection.get("ID");
assertEquals("502", actId.asText());
final ObjectNode complex = (ObjectNode) collection.get("FirstLevel");
assertFalse(complex.get("SecondLevel") instanceof NullNode);
final ObjectNode second = (ObjectNode) complex.get("SecondLevel");
final ArrayNode comment = (ArrayNode) second.get("Comment");
assertEquals(2, comment.size());
final ArrayNode address = (ArrayNode) second.get("Address");
assertNotNull(address);
}
@Test
void testSelectOnlyNoCollectionDeepComplex() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('501')?$select=FirstLevel/SecondLevel/Number");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final TextNode actId = (TextNode) collection.get("ID");
assertEquals("501", actId.asText());
final ObjectNode second = assertDeepCollectionSecondLevel(collection);
final IntNode number = (IntNode) second.get("Number");
assertEquals(-1, number.asInt());
}
@Test
void testSelectOneCollectionPropertyViaDeepPath() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('501')/FirstLevel/SecondLevel?$select=Comment");
helper.assertStatus(200);
final ObjectNode second = helper.getValue();
final ArrayNode comment = (ArrayNode) second.get("Comment");
assertTrue(comment.size() > 0);
}
@Test
void testSelectTwoCollectionPropertyViaDeepPath() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('501')/FirstLevel/SecondLevel?$select=Address,Comment");
helper.assertStatus(200);
final ObjectNode second = helper.getValue();
final ArrayNode comment = (ArrayNode) second.get("Comment");
assertTrue(comment.size() > 0);
final ArrayNode addresses = (ArrayNode) second.get("Address");
assertTrue(addresses.size() > 0);
}
@Test
void testSelectAllCollectionPropertyViaDeepPath() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('501')/FirstLevel/SecondLevel");
helper.assertStatus(200);
final ObjectNode second = helper.getValue();
final ArrayNode comment = (ArrayNode) second.get("Comment");
assertTrue(comment.size() > 0);
final ArrayNode addresses = (ArrayNode) second.get("Address");
assertTrue(addresses.size() > 0);
}
@Test
void testSelectOneCollectionPropertyViaPath() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('501')/FirstLevel?$select=SecondLevel/Comment");
helper.assertStatus(200);
final ObjectNode first = helper.getValue();
final ObjectNode secondLevel = (ObjectNode) first.get("SecondLevel");
final ArrayNode comment = (ArrayNode) secondLevel.get("Comment");
assertTrue(comment.size() > 0);
}
@Test
void testSelectCollectionWithoutRequiredGroup() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerWithGroupss('1')?$select=Comment");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = (ArrayNode) collection.get("Comment");
assertEquals(0, act.size());
}
@Test
void testSelectCollectionWithRequiredGroup() throws IOException, ODataException {
final JPAODataGroupsProvider groups = new JPAODataGroupsProvider();
groups.addGroup("Company");
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"BusinessPartnerWithGroupss('1')?$select=Comment", groups);
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = (ArrayNode) collection.get("Comment");
assertEquals(2, act.size());
}
@Test
void testSelectCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('1')?$select=Comment");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = (ArrayNode) collection.get("Comment");
assertEquals(2, act.size());
}
@Test
void testSelectCollectionWithTop() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$select=Comment&$top=2");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = ((ArrayNode) collection.get("value"));
assertEquals(2, act.size());
assertEquals(2, act.get(0).get("Comment").size());
assertEquals("1", act.get(0).get("ID").asText());
}
@Test
void testSelectCollectionWithTopAndOrderBy() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations?$select=Comment&$top=2&orderby=Name1");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode act = ((ArrayNode) collection.get("value"));
assertEquals(2, act.size());
assertEquals(2, act.get(0).get("Comment").size());
}
@Test
void testPathWithTransientCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "CollectionDeeps('501')/FirstLevel");
helper.assertStatus(200);
// CollectionDeep.class
final ObjectNode complex = helper.getValue();
assertEquals(1, complex.get("LevelID").asInt());
assertFalse(complex.get("SecondLevel") instanceof NullNode);
assertEquals(2, complex.get("TransientCollection").size());
}
@Test
void testPathToTransientCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('501')/FirstLevel/TransientCollection"); // SecondLevel/Address"); //
helper.assertStatus(200);
// CollectionDeep.class
final ObjectNode result = helper.getValue();
final ArrayNode collection = (ArrayNode) result.get("value");
assertEquals(2, collection.size());
}
@Test
void testPathToTransientCollectionWoRequired() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionWithTransients('501')/TransientComment");
helper.assertStatus(200);
// CollectionDeep.class
final ObjectNode result = helper.getValue();
final ArrayNode collection = (ArrayNode) result.get("value");
assertEquals(2, collection.size());
}
@Test
void testPathWithCollections() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('501')/FirstLevel/SecondLevel");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode complex = (ArrayNode) collection.get("Address");
assertEquals(1, complex.size());
}
@Test
void testPathToCollectionWithTransient() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionWithTransients('501')/Nested"); // $select=Log");
helper.assertStatus(200);
final ObjectNode result = helper.getValue();
final ArrayNode collection = (ArrayNode) result.get("value");
assertEquals(2, collection.size());
assertFalse(collection.get(0).get("Log") instanceof NullNode);
}
@Test
void testSelectTransientOfCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionWithTransients('501')/Nested$select=Log");
helper.assertStatus(200);
final ObjectNode result = helper.getValue();
final ArrayNode collection = (ArrayNode) result.get("value");
assertEquals(2, collection.size());
assertFalse(collection.get(0).get("Log") instanceof NullNode);
}
@Test
void testSelectCollectionContainsTransient() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionWithTransients('501')");
helper.assertStatus(200);
}
@Test
void testPathToCollections() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CollectionDeeps('501')/FirstLevel/SecondLevel/Address");
helper.assertStatus(200);
final ObjectNode collection = helper.getValue();
final ArrayNode complex = (ArrayNode) collection.get("value");
assertEquals(1, complex.size());
}
@Test
void testSelectCollectionCountSimpleProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Organizations('1')/Comment/$count");
helper.assertStatus(200);
final ValueNode count = helper.getSingleValue();
assertEquals(2, count.asInt());
}
@Test
void testSelectCollectionCountComplexProperty() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"Persons('99')/InhouseAddress/$count");
helper.assertStatus(200);
final ValueNode count = helper.getSingleValue();
assertEquals(2, count.asInt());
}
@Test
void testSelectCollectionCountComplexPropertySingleton() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf,
"CurrentUser/InhouseAddress/$count");
helper.assertStatus(200);
final ValueNode count = helper.getSingleValue();
assertEquals(1, count.asInt());
}
private ObjectNode assertDeepCollectionSecondLevel(final ObjectNode collection) {
final ObjectNode complex = (ObjectNode) collection.get("FirstLevel");
assertFalse(complex.get("SecondLevel") instanceof NullNode);
return (ObjectNode) complex.get("SecondLevel");
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryHandlesETag.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryHandlesETag.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestJPAQueryHandlesETag extends TestBase {
static Stream<Arguments> containsETag() {
return Stream.of(
arguments("Single entity", "Organizations('3')"),
arguments("Single entity eTag not selected", "Organizations('3')?$select=ID"),
arguments("Collection one result", "Organizations?$filter=ID eq '3'"));
}
@ParameterizedTest
@MethodSource("containsETag")
void testResultContainsETagHeader(final String test, final String url) throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, url);
helper.assertStatus(200);
assertNotNull(helper.getHeader(HttpHeader.ETAG), test);
assertTrue(helper.getHeader(HttpHeader.ETAG).startsWith("\""));
assertTrue(helper.getHeader(HttpHeader.ETAG).endsWith("\""));
}
@Test
void testResultNotContainsETagHeader() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations");
helper.assertStatus(200);
assertNull(helper.getHeader(HttpHeader.ETAG));
}
@Test
void testIfNoneMatchHeaderNotModified() throws IOException, ODataException {
final Map<String, List<String>> headers = new HashMap<>();
headers.put(HttpHeader.IF_NONE_MATCH, Arrays.asList("\"0\""));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')", headers);
helper.assertStatus(304);
assertNotNull(helper.getHeader(HttpHeader.ETAG), "\"0\"");
assertTrue(helper.getRawResult().isBlank());
}
@Test
void testIfMatchHeaderPreconditionFailed() throws IOException, ODataException {
final Map<String, List<String>> headers = new HashMap<>();
headers.put(HttpHeader.IF_MATCH, Arrays.asList("\"2\""));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')", headers);
helper.assertStatus(412);
assertTrue(helper.getRawResult().isBlank());
}
@Test
void testIfMatchHeaderUnknownNotFound() throws IOException, ODataException {
final Map<String, List<String>> headers = new HashMap<>();
headers.put(HttpHeader.IF_MATCH, Arrays.asList("\"2\""));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1000')", headers);
helper.assertStatus(404);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandJoinQueryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/JPAExpandJoinQueryTest.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAKeyPairException;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole;
class JPAExpandJoinQueryTest extends JPAExpandQueryTest {
@Test
void testSelectAllWithAllExpand() throws ODataException {
// .../Organizations?$expand=Roles&$format=json
final JPAInlineItemInfo item = createOrganizationExpandRoles(null);
cut = new JPAExpandJoinQuery(OData.newInstance(), item, requestContext, Optional.empty());
final JPAExpandQueryResult act = cut.execute();
assertEquals(4, act.getNoResults());
assertEquals(7, act.getNoResultsDeep());
}
@Test
void testSelectDistinctExpand() throws ODataException {
// .../BusinessPartnerRoles?$expand=BusinessPartner($select=ID;$expand=Roles)
final JPAInlineItemInfo item = createBusinessParterRolesExpandChildrenParent(null);
cut = new JPAExpandJoinQuery(OData.newInstance(), item, requestContext, Optional.empty());
final JPAExpandQueryResult act = cut.execute();
assertEquals(7, act.getNoResults());
assertEquals(11, act.getNoResultsDeep());
}
@Test
void testSelectWithMinBoundary() throws ODataException {
// .../Organizations?$expand=Roles&$skip=2&$format=json
final JPAInlineItemInfo item = createOrganizationExpandRoles(null);
setSimpleKey(3);
cut = new JPAExpandJoinQuery(OData.newInstance(), item, requestContext, organizationBoundary);
final JPAExpandQueryResult act = cut.execute();
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().contains(".\"ID\" = ?"));
assertEquals(1, act.getNoResults());
assertEquals(3, act.getNoResultsDeep());
}
@Test
void testSelectWithMinBoundaryEmbedded() throws ODataException {
// .../Organizations?$expand=Roles&$skip=2&$format=json
final JPAInlineItemInfo item = createAdminDivExpandChildren(null);
setComplexKey("Eurostat", "NUTS1", "BE2");
cut = new JPAExpandJoinQuery(OData.newInstance(), item, requestContext, adminBoundary);
final JPAExpandQueryResult act = cut.execute();
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().contains(
"(((t1.\"DivisionCode\" = ?) AND (t1.\"CodeID\" = ?)) AND (t1.\"CodePublisher\" = ?)) "));
assertEquals(1, act.getNoResults());
assertEquals(5, act.getNoResultsDeep());
}
@Test
void testSelectWithMinMaxBoundary() throws ODataException {
// .../Organizations?$expand=Roles&$top=3&$format=json
final JPAInlineItemInfo item = createOrganizationExpandRoles(null);
setSimpleKey(2);
setSimpleKey(1);
cut = new JPAExpandJoinQuery(OData.newInstance(), item, requestContext, organizationBoundary);
final JPAExpandQueryResult act = cut.execute();
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().contains(".\"ID\" >= ?"));
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().contains(".\"ID\" <= ?"));
assertEquals(2, act.getNoResults());
assertEquals(3, act.getNoResultsDeep());
}
@Test
void testSelectWithMinMaxBoundaryEmbeddedOnlyLastDiffers() throws ODataException {
final JPAInlineItemInfo item = createAdminDivExpandChildren(null);
setComplexKey("Eurostat", "NUTS1", "BE1");
setComplexKey("Eurostat", "NUTS2", "BE25");
cut = new JPAExpandJoinQuery(OData.newInstance(), item, requestContext, adminBoundary);
final JPAExpandQueryResult act = cut.execute();
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().contains(
"OR (((t1.\"CodePublisher\" = ?) AND (t1.\"CodeID\" = ?)) AND (t1.\"DivisionCode\" >= ?)))"));
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().contains(
"OR (((t1.\"CodePublisher\" = ?) AND (t1.\"CodeID\" = ?)) AND (t1.\"DivisionCode\" <= ?)))"));
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().contains(
"OR ((((t1.\"CodePublisher\" = ?) AND (t1.\"CodePublisher\" = ?)) AND (t1.\"CodeID\" > ?)) AND (t1.\"CodeID\" < ?)))"));
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().contains(
"((t1.\"CodePublisher\" > ?) AND (t1.\"CodePublisher\" < ?))"));
assertEquals(9, act.getNoResults());
assertEquals(34, act.getNoResultsDeep());
}
@Test
void testSQLStringNotEmptyAfterExecute() throws ODataException {
// .../Organizations?$expand=Roles&$format=json
final JPAInlineItemInfo item = createOrganizationExpandRoles(null);
cut = new JPAExpandJoinQuery(OData.newInstance(), item, requestContext, Optional.empty());
assertTrue(((JPAExpandJoinQuery) cut).getSQLString().isEmpty());
cut.execute();
assertFalse(((JPAExpandJoinQuery) cut).getSQLString().isEmpty());
}
private JPAInlineItemInfo createAdminDivExpandChildren(final List<UriParameter> keyPredicates)
throws ODataJPAModelException, ODataApplicationException {
final JPAEntityType et = helper.getJPAEntityType("AdministrativeDivisions");
final JPAExpandItemWrapper uriInfo = mock(JPAExpandItemWrapper.class);
final UriResourceEntitySet uriEts = mock(UriResourceEntitySet.class);
when(uriEts.getKeyPredicates()).thenReturn(keyPredicates);
final EdmEntityType edmType = mock(EdmEntityType.class);
final EdmEntitySet edmSet = mock(EdmEntitySet.class);
final List<JPANavigationPropertyInfo> hops = new ArrayList<>();
JPANavigationPropertyInfo hop = new JPANavigationPropertyInfo(helper.sd, uriEts, et.getAssociationPath(
"Children"), null);
hops.add(hop);
final JPAInlineItemInfo item = mock(JPAInlineItemInfo.class);
final UriResourceNavigation target = mock(UriResourceNavigation.class);
final EdmNavigationProperty targetProperty = mock(EdmNavigationProperty.class);
when(targetProperty.getName()).thenReturn("Children");
when(target.getProperty()).thenReturn(targetProperty);
final List<UriResource> resourceParts = new ArrayList<>();
resourceParts.add(target);
hop = new JPANavigationPropertyInfo(helper.sd, null, null, et);
hops.add(hop);
when(item.getEntityType()).thenReturn(et);
when(item.getUriInfo()).thenReturn(uriInfo);
when(item.getHops()).thenReturn(hops);
when(item.getExpandAssociation()).thenReturn(et.getAssociationPath("Children"));
when(uriInfo.getUriResourceParts()).thenReturn(resourceParts);
when(uriEts.getType()).thenReturn(edmType);
when(uriEts.getEntitySet()).thenReturn(edmSet);
when(edmSet.getName()).thenReturn("AdministrativeDivisions");
when(edmType.getNamespace()).thenReturn(PUNIT_NAME);
when(edmType.getName()).thenReturn("AdministrativeDivision");
return item;
}
private JPAInlineItemInfo createBusinessParterRolesExpandChildrenParent(final List<UriParameter> keyPredicates)
throws ODataJPAModelException, ODataApplicationException {
// .../BusinessPartnerRoles?$expand=BusinessPartner($select=ID;$expand=Roles)
final JPAEntityType et = helper.getJPAEntityType(BusinessPartnerRole.class);
final JPAEntityType buPaEt = helper.getJPAEntityType(BusinessPartner.class);
final JPAExpandItemWrapper uriInfo = mock(JPAExpandItemWrapper.class);
final UriResourceEntitySet uriEts = mock(UriResourceEntitySet.class);
when(uriEts.getKeyPredicates()).thenReturn(keyPredicates);
final EdmEntityType edmType = mock(EdmEntityType.class);
final EdmEntitySet edmSet = mock(EdmEntitySet.class);
final List<JPANavigationPropertyInfo> hops = new ArrayList<>();
hops.add(new JPANavigationPropertyInfo(helper.sd, uriEts, et.getAssociationPath(
"BusinessPartner"), null));
hops.add(new JPANavigationPropertyInfo(helper.sd, buPaEt.getAssociationPath(
"Roles"), null, buPaEt));
hops.add(new JPANavigationPropertyInfo(helper.sd, null, null, et));
final JPAInlineItemInfo item = mock(JPAInlineItemInfo.class);
final UriResourceNavigation target = mock(UriResourceNavigation.class);
final EdmNavigationProperty targetProperty = mock(EdmNavigationProperty.class);
when(targetProperty.getName()).thenReturn("Roles");
when(target.getProperty()).thenReturn(targetProperty);
final List<UriResource> resourceParts = new ArrayList<>();
resourceParts.add(target);
when(item.getEntityType()).thenReturn(et);
when(item.getUriInfo()).thenReturn(uriInfo);
when(item.getHops()).thenReturn(hops);
when(item.getExpandAssociation()).thenReturn(buPaEt.getAssociationPath("Roles"));
when(uriInfo.getUriResourceParts()).thenReturn(resourceParts);
when(uriEts.getType()).thenReturn(edmType);
when(uriEts.getEntitySet()).thenReturn(edmSet);
when(edmSet.getName()).thenReturn("BusinessPartnerRoles");
when(edmType.getNamespace()).thenReturn(PUNIT_NAME);
when(edmType.getName()).thenReturn("BusinessPartnerRole");
return item;
}
private void setSimpleKey(final Integer value) throws ODataJPAModelException, ODataJPAKeyPairException {
simpleKey = new HashMap<>(1);
simpleKey.put(helper.getJPAEntityType("Organizations").getKey().get(0), value);
organizationPair.setValue(simpleKey);
}
private void setComplexKey(final String key1, final String key2, final String key3)
throws ODataJPAModelException, ODataJPAKeyPairException {
simpleKey = new HashMap<>(3);
final JPAEntityType et = helper.getJPAEntityType("AdministrativeDivisions");
simpleKey.put(et.getKey().get(0), key1);
simpleKey.put(et.getKey().get(1), key2);
simpleKey.put(et.getKey().get(2), key3);
adminPair.setValue(simpleKey);
}
@Override
protected JPAExpandQuery createCut(final JPAInlineItemInfo item) throws ODataException {
return new JPAExpandJoinQuery(OData.newInstance(), item, requestContext, Optional.empty());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.apache.olingo.server.api.uri.queryoption.OrderByItem;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SelectItem;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.matcher.CountQueryMatcher;
class TestJPAServerDrivenPaging extends TestBase {
@Test
void testReturnsGoneIfPagingProviderNotAvailable() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz");
helper.assertStatus(410);
}
@Test
void testReturnsGoneIfPagingProviderReturnsNullForSkipToken() throws IOException, ODataException {
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getNextPage(eq("xyz"), any(), any(), any(), any())).thenReturn(Optional.empty());
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz", provider);
helper.assertStatus(410);
}
@Test
void testReturnsFullResultIfProviderDoesNotReturnPage() throws IOException, ODataException {
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any())).thenReturn(Optional.empty());
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations", provider);
helper.assertStatus(200);
assertEquals(10, helper.getValues().size());
}
@Test
void testReturnsPartResultIfProviderPages() throws IOException, ODataException {
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider);
helper.assertStatus(200);
assertEquals(5, helper.getValues().size());
}
@Test
void testReturnsNextLinkIfProviderPages() throws IOException, ODataException {
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider);
helper.assertStatus(200);
assertEquals(5, helper.getValues().size());
// No difference between Sting an other types of skip tokens
assertEquals("Organizations?$skiptoken=Hugo", helper.getValue().get("@odata.nextLink").asText());
}
@Test
void testReturnsNextLinkNotAStringIfProviderPages() throws IOException, ODataException {
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, Integer.valueOf(
123456789))));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider);
helper.assertStatus(200);
assertEquals(5, helper.getValues().size());
assertEquals("Organizations?$skiptoken=123456789", helper.getValue().get("@odata.nextLink").asText());
}
@Test
void testReturnsNextPagesRespectingFilter() throws IOException, ODataException {
final UriInfo uriInfo = buildUriInfo();
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getNextPage(eq("xyz"), any(), any(), any(), any()))
.thenReturn(Optional.of(new JPAODataPage(uriInfo, 5, 5, null)));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz", provider);
helper.assertStatus(200);
assertEquals(5, helper.getValues().size());
final ObjectNode organization = (ObjectNode) helper.getValues().get(4);
assertEquals("1", organization.get("ID").asText());
}
@Test
void testEntityManagerProvided() throws IOException, ODataException {
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider);
helper.assertStatus(200);
verify(provider).getFirstPage(any(), any(), any(), any(), any(), notNull());
}
@Test
void testCountQueryProvided() throws IOException, ODataException {
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider);
helper.assertStatus(200);
verify(provider).getFirstPage(any(), any(), any(), any(), notNull(), any());
}
@Test
void testCountQueryProvidedWithProtection() throws IOException, ODataException {
final JPAODataClaimsProvider claims = new JPAODataClaimsProvider();
claims.add("UserId", new JPAClaimsPair<>("Willi"));
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "BusinessPartnerProtecteds", provider, claims);
helper.assertStatus(200);
final ArrayNode act = helper.getValues();
assertEquals(3, act.size());
verify(provider).getFirstPage(any(), any(), any(), any(), argThat(new CountQueryMatcher(3L)), any());
}
@Test
void testMaxPageSizeHeaderProvided() throws IOException, ODataException {
headers = new HashMap<>();
final List<String> headerValues = new ArrayList<>(0);
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
headerValues.add("odata.maxpagesize=50");
headers.put("Prefer", headerValues);
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider,
headers);
helper.assertStatus(200);
verify(provider).getFirstPage(any(), any(), any(), notNull(), any(), any());
}
@Test
void testMaxPageSizeHeaderProvidedInLowerCase() throws IOException, ODataException {
headers = new HashMap<>();
final List<String> headerValues = new ArrayList<>(0);
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
headerValues.add("odata.maxpagesize=50");
headers.put("prefer", headerValues);
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider,
headers);
helper.assertStatus(200);
verify(provider).getFirstPage(any(), any(), any(), notNull(), any(), any());
}
@Test
void testUriInfoProvided() throws IOException, ODataException {
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider);
helper.assertStatus(200);
verify(provider).getFirstPage(any(), any(), notNull(), any(), any(), any());
}
@Test
void testMaxPageSiteHeaderNotANumber() throws IOException, ODataException {
headers = new HashMap<>();
final List<String> headerValues = new ArrayList<>(0);
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
when(provider.getFirstPage(any(), any(), any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i
.getArguments()[2], 0, 5, "Hugo"));
headerValues.add("odata.maxpagesize=Hugo");
headers.put("Prefer", headerValues);
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider,
headers);
helper.assertStatus(400);
}
@Test
void testSelectSubsetOfFields() throws IOException, ODataException {
final UriInfo uriInfo = buildUriInfo();
final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class);
final SelectOption selectOpt = mock(SelectOption.class);
final List<SelectItem> selectItems = new ArrayList<>();
final SelectItem selectItem = mock(SelectItem.class);
when(uriInfo.getSelectOption()).thenReturn(selectOpt);
when(uriInfo.getSystemQueryOptions()).thenReturn(Collections.singletonList(selectOpt));
when(selectOpt.getKind()).thenReturn(SystemQueryOptionKind.SELECT);
when(selectOpt.getSelectItems()).thenReturn(selectItems);
selectItems.add(selectItem);
final UriInfoResource selectPath = mock(UriInfoResource.class);
final List<UriResource> selectPathItems = new ArrayList<>(0);
final UriResourcePrimitiveProperty selectResource = mock(UriResourcePrimitiveProperty.class);
final EdmProperty selectProperty = mock(EdmProperty.class);
selectPathItems.add(selectResource);
when(selectItem.getResourcePath()).thenReturn(selectPath);
when(selectPath.getUriResourceParts()).thenReturn(selectPathItems);
when(selectResource.getSegmentValue()).thenReturn("ID");
when(selectResource.getProperty()).thenReturn(selectProperty);
when(selectProperty.getName()).thenReturn("ID");
when(provider.getFirstPage(any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> Optional.of(new JPAODataPage((UriInfo) i.getArguments()[2], 0, 5, "Hugo")));
when(provider.getNextPage(eq("'Hugo'"), any(), any(), any(), any()))
.thenReturn(Optional.of(new JPAODataPage(uriInfo, 5, 5, "Willi")));
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc&$select=ID",
provider);
helper.assertStatus(200);
assertNull(helper.getValues().get(0).get("Country"));
final IntegrationTestHelper act = new IntegrationTestHelper(emf, "Organizations?$skiptoken='Hugo'",
provider);
act.assertStatus(200);
assertEquals(5, act.getValues().size());
assertNull(act.getValues().get(0).get("Country"));
}
private UriInfo buildUriInfo() throws EdmPrimitiveTypeException {
final UriInfo uriInfo = mock(UriInfo.class);
final UriResourceEntitySet uriEs = mock(UriResourceEntitySet.class);
final EdmEntitySet es = mock(EdmEntitySet.class);
final EdmEntityType et = mock(EdmEntityType.class);
final EdmType type = mock(EdmType.class);
final OrderByOption order = mock(OrderByOption.class);
final OrderByItem orderItem = mock(OrderByItem.class);
final Member orderExpression = mock(Member.class);
final UriInfoResource orderResourcePath = mock(UriInfoResource.class);
final UriResourcePrimitiveProperty orderResourcePathItem = mock(UriResourcePrimitiveProperty.class);
final EdmProperty orderProperty = mock(EdmProperty.class);
final List<OrderByItem> orderItems = new ArrayList<>();
final List<UriResource> orderResourcePathItems = new ArrayList<>();
final EdmProperty propertyID = mock(EdmProperty.class); // type.getStructuralProperty(propertyName);
final EdmProperty propertyCountry = mock(EdmProperty.class);
final EdmPrimitiveType propertyType = mock(EdmPrimitiveType.class);
orderItems.add(orderItem);
orderResourcePathItems.add(orderResourcePathItem);
when(uriEs.getKind()).thenReturn(UriResourceKind.entitySet);
when(uriEs.getEntitySet()).thenReturn(es);
when(uriEs.getType()).thenReturn(type);
when(uriEs.isCollection()).thenReturn(true);
when(es.getName()).thenReturn("Organizations");
when(es.getEntityType()).thenReturn(et);
when(type.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(type.getName()).thenReturn("Organization");
when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName("com.sap.olingo.jpa", "Organization"));
when(et.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(et.getName()).thenReturn("Organization");
when(et.getPropertyNames()).thenReturn(Arrays.asList("ID", "Country"));
when(et.getStructuralProperty("ID")).thenReturn(propertyID);
when(et.getStructuralProperty("Country")).thenReturn(propertyCountry);
when(propertyID.getName()).thenReturn("ID");
when(propertyID.isPrimitive()).thenReturn(true);
when(propertyID.getType()).thenReturn(propertyType);
when(propertyCountry.getName()).thenReturn("Country");
when(propertyCountry.isPrimitive()).thenReturn(true);
when(propertyCountry.getType()).thenReturn(propertyType);
when(propertyType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE);
when(propertyType.valueToString(any(), any(), any(), any(), any(), any())).thenAnswer(i -> i.getArguments()[0]
.toString());
when(order.getKind()).thenReturn(SystemQueryOptionKind.ORDERBY);
when(orderItem.isDescending()).thenReturn(true);
when(orderItem.getExpression()).thenReturn(orderExpression);
when(orderExpression.getResourcePath()).thenReturn(orderResourcePath);
when(orderResourcePath.getUriResourceParts()).thenReturn(orderResourcePathItems);
when(orderResourcePathItem.getProperty()).thenReturn(orderProperty);
when(orderResourcePathItem.getKind()).thenReturn(UriResourceKind.primitiveProperty);
when(orderProperty.getName()).thenReturn("ID");
when(order.getOrders()).thenReturn(orderItems);
final List<UriResource> resourceParts = new ArrayList<>();
resourceParts.add(uriEs);
when(uriInfo.getUriResourceParts()).thenReturn(resourceParts);
when(uriInfo.getOrderByOption()).thenReturn(order);
when(uriInfo.getSystemQueryOptions()).thenReturn(Arrays.asList(order));
return uriInfo;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java | package com.sap.olingo.jpa.processor.core.query;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
class TestJPAFunctionSerializer {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
protected static EntityManagerFactory emf;
protected static DataSource ds;
protected Map<String, List<String>> headers;
@BeforeEach
void setup() {
ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB);
final Map<String, Object> properties = new HashMap<>();
properties.put("jakarta.persistence.nonJtaDataSource", ds);
emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties);
emf.getProperties();
}
@Test
void testFunctionReturnsEntityType() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityType(A=1250)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ObjectNode r = helper.getValue();
assertNotNull(r.get("Area"));
assertEquals(1250, r.get("Area").asInt());
}
@Test
void testFunctionReturnsEntityTypeNull() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityType(A=0)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(204);
}
@Test
void testFunctionReturnsEntityTypeCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfEntityType(A=1250)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ObjectNode r = helper.getValue();
final ArrayNode values = (ArrayNode) r.get("value");
assertNotNull(values.get(0));
assertNotNull(values.get(0).get("Area"));
assertEquals(1250, values.get(0).get("Area").asInt());
assertNotNull(values.get(1));
assertNotNull(values.get(1).get("Area"));
assertEquals(625, values.get(1).get("Area").asInt());
}
@Test
void testFunctionReturnsPrimitiveType() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "PrimitiveValue(A=124)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ObjectNode r = helper.getValue();
assertNotNull(r);
assertNotNull(r.get("value"));
assertEquals(124, r.get("value").asInt());
}
@Test
void testFunctionReturnsPrimitiveTypeNull() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "PrimitiveValue(A=0)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(204);
}
@Test
void testFunctionReturnsPrimitiveTypeCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfPrimitiveValues(A=124)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ArrayNode r = helper.getValues();
assertNotNull(r);
assertNotNull(r.get(0));
assertEquals(124, r.get(0).asInt());
assertNotNull(r.get(1));
assertEquals(62, r.get(1).asInt());
}
@Test
void testFunctionReturnsComplexType() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ComplexType(A=124)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ObjectNode r = helper.getValue();
assertNotNull(r);
assertNotNull(r.get("LandlinePhoneNumber"));
assertEquals(124, r.get("LandlinePhoneNumber").asInt());
}
@Test
void testFunctionReturnsComplexTypeNull() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ComplexType(A=0)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(204);
}
@Test
void testFunctionReturnsComplexTypeCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfComplexType(A='Willi')",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ArrayNode r = helper.getValues();
assertNotNull(r);
assertNotNull(r.get(0));
assertNotNull(r.get(0).get("Created"));
}
@Test
void testUsesConverter() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ConvertBirthday()",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
}
@Test
void testFunctionReturnsEntityTypeWithCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfEntityTypeWithCollection(A=1250)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ObjectNode r = helper.getValue();
assertNotNull(r.get("value"));
final ObjectNode person = (ObjectNode) r.get("value").get(0);
final ArrayNode addr = (ArrayNode) person.get("InhouseAddress");
assertEquals(2, addr.size());
}
@Test
void testFunctionReturnsEntityTypeWithDeepCollection() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityTypeWithDeepCollection(A=1250)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ObjectNode r = helper.getValue();
assertNotNull(r);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataEtagHelperImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataEtagHelperImplTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
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.sql.Timestamp;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.etag.ETagHelper;
import org.apache.olingo.server.api.etag.PreconditionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEtagValidator;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
class JPAODataEtagHelperImplTest {
// See org.apache.olingo.server.core.etag.ETagParser
private static final Pattern ETAG = Pattern.compile("\\s*(,\\s*)+|((?:W/)?\"[!#-~\\x80-\\xFF]*\")");
private JPAODataEtagHelperImpl cut;
private OData odata;
private ETagHelper olingoHelper;
@BeforeEach
void setup() {
odata = mock(OData.class);
olingoHelper = mock(ETagHelper.class);
when(odata.createETagHelper()).thenReturn(olingoHelper);
cut = new JPAODataEtagHelperImpl(odata);
}
@Test
void testCheckReadPreconditionsCallsOlingo() throws PreconditionException {
final String etag = "";
final Collection<String> ifMatchHeaders = Collections.emptyList();
final Collection<String> ifNoneMatchHeaders = Collections.emptyList();
cut.checkReadPreconditions(etag, ifMatchHeaders, ifNoneMatchHeaders);
verify(olingoHelper, times(1)).checkReadPreconditions(etag, ifMatchHeaders, ifNoneMatchHeaders);
}
@Test
void testCheckChangePreconditionsCallsOlingo() throws PreconditionException {
final String etag = "";
final Collection<String> ifMatchHeaders = Collections.emptyList();
final Collection<String> ifNoneMatchHeaders = Collections.emptyList();
cut.checkChangePreconditions(etag, ifMatchHeaders, ifNoneMatchHeaders);
verify(olingoHelper, times(1)).checkChangePreconditions(etag, ifMatchHeaders, ifNoneMatchHeaders);
}
@Test
void testAsEtagStringStrong() throws ODataJPAModelException, ODataJPAQueryException {
final JPAEntityType et = createEntityType("Person", true, JPAEtagValidator.STRONG);
final var act = cut.asEtag(et, 12L);
assertEquals("\"12\"", act);
assertEtagConsistent(act);
}
@Test
void testAsEtagStringWeak() throws ODataJPAModelException, ODataJPAQueryException {
final JPAEntityType et = createEntityType("Person", true, JPAEtagValidator.WEAK);
final var act = cut.asEtag(et, 12L);
assertEquals("W/\"12\"", act);
assertEtagConsistent(act);
}
@Test
void testAsEtagStringTimestamp() throws ODataJPAModelException, ODataJPAQueryException {
final JPAEntityType et = createEntityType("Person", true, JPAEtagValidator.WEAK);
final Instant i = Instant.now();
final var act = cut.asEtag(et, Timestamp.from(i));
assertEquals("W/\"" + i.toString() + "\"", act);
assertEtagConsistent(act);
}
@Test
void testAsEtagStringValueNullEmptyString() throws ODataJPAModelException, ODataJPAQueryException {
final JPAEntityType et = createEntityType("Person", true, JPAEtagValidator.WEAK);
final var act = cut.asEtag(et, null);
assertEquals("", act);
}
@Test
void testAsEtagStringEntityTypeNoEtag() throws ODataJPAModelException, ODataJPAQueryException {
final JPAEntityType et = createEntityType("Person", false, JPAEtagValidator.STRONG);
final var act = cut.asEtag(et, null);
assertNull(act);
}
private JPAEntityType createEntityType(final String name, final boolean hasEtag, final JPAEtagValidator validator)
throws ODataJPAModelException {
final var et = mock(JPAEntityType.class);
when(et.getExternalName()).thenReturn(name);
when(et.hasEtag()).thenReturn(hasEtag);
when(et.getEtagValidator()).thenReturn(validator);
return et;
}
private void assertEtagConsistent(final String value) {
final Matcher matcher = ETAG.matcher(value.trim());
assertTrue(matcher.matches(), "Match: " + matcher.find());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPADebugSupportWrapperTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPADebugSupportWrapperTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.debug.DebugInformation;
import org.apache.olingo.server.api.debug.DebugSupport;
import org.apache.olingo.server.api.debug.RuntimeMeasurement;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
class JPADebugSupportWrapperTest {
private static final String DEBUG_FORMAT = "JSON";
private JPADebugSupportWrapper cut;
private DebugSupport warpped;
private OData odata;
@BeforeEach
void setup() {
warpped = mock(DebugSupport.class);
odata = OData.newInstance();
cut = new JPADebugSupportWrapper(warpped);
}
@Test
void testInitForwarded() {
cut.init(odata);
verify(warpped, times(1)).init(odata);
}
@Test
void testIsUserAuthorizedForwarded() {
cut.isUserAuthorized();
verify(warpped, times(1)).isUserAuthorized();
}
@Test
void testCreateDebugResponse() {
final DebugInformation debugInfo = mock(DebugInformation.class);
final JPAServiceDebugger debugger = mock(JPAServiceDebugger.class);
cut.addDebugger(debugger);
final RuntimeMeasurement first = newRuntimeMeasurement();
final RuntimeMeasurement second = newRuntimeMeasurement();
final RuntimeMeasurement third = newRuntimeMeasurement();
final List<RuntimeMeasurement> debugInfoList = new ArrayList<>(
Arrays.asList(first, third));
final List<RuntimeMeasurement> debuggerList = Arrays.asList(second);
when(debugInfo.getRuntimeInformation()).thenReturn(debugInfoList);
when(debugger.getRuntimeInformation()).thenReturn(debuggerList);
cut.createDebugResponse(DEBUG_FORMAT, debugInfo);
assertEquals(3, debugInfoList.size());
}
private RuntimeMeasurement newRuntimeMeasurement() {
final RuntimeMeasurement r = new RuntimeMeasurement();
r.setTimeStarted(System.nanoTime());
return r;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.core.edm.primitivetype.EdmString;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.ArgumentMatchers;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.JPAReferences;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory.JPAODataTransaction;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
import com.sap.olingo.jpa.processor.core.query.EdmBindingTargetInfo;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.util.TestBase;
abstract class TestJPAModifyProcessor {
protected static final String LOCATION_HEADER = "Organization('35')";
protected static final String PREFERENCE_APPLIED = "return=minimal";
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
protected static EntityManagerFactory emf;
protected static JPAEdmProvider jpaEdm;
protected static DataSource ds;
protected static List<AnnotationProvider> annotationProvider;
protected static JPAReferences references;
@BeforeAll
public static void setupClass() throws ODataException {
final JPAEdmMetadataPostProcessor pP = mock(JPAEdmMetadataPostProcessor.class);
annotationProvider = new ArrayList<>();
ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds);
jpaEdm = new JPAEdmProvider(PUNIT_NAME, emf.getMetamodel(), pP, TestBase.enumPackages, annotationProvider);
}
protected JPACUDRequestProcessor processor;
protected OData odata;
protected ServiceMetadata serviceMetadata;
protected JPAODataRequestContextAccess requestContext;
protected UriInfo uriInfo;
protected UriResourceEntitySet uriEts;
protected EntityManager em;
protected JPAODataTransaction transaction;
protected JPASerializer serializer;
protected EdmEntitySet ets;
protected EdmBindingTargetInfo etsInfo;
protected List<UriParameter> keyPredicates;
protected JPAConversionHelper convHelper;
protected List<UriResource> pathParts = new ArrayList<>();
protected SerializerResult serializerResult;
protected List<String> header = new ArrayList<>();
protected JPAServiceDebugger debugger;
protected JPAODataTransactionFactory factory;
@BeforeEach
public void setup() throws Exception {
odata = OData.newInstance();
requestContext = mock(JPAODataRequestContextAccess.class);
serviceMetadata = mock(ServiceMetadata.class);
uriInfo = mock(UriInfo.class);
keyPredicates = new ArrayList<>();
ets = mock(EdmEntitySet.class);
etsInfo = mock(EdmBindingTargetInfo.class);
serializer = mock(JPASerializer.class);
uriEts = mock(UriResourceEntitySet.class);
pathParts.add(uriEts);
convHelper = mock(JPAConversionHelper.class);
em = mock(EntityManager.class);
transaction = mock(JPAODataTransaction.class);
serializerResult = mock(SerializerResult.class);
debugger = mock(JPAServiceDebugger.class);
factory = mock(JPAODataTransactionFactory.class);
when(requestContext.getEdmProvider()).thenReturn(jpaEdm);
when(requestContext.getDebugger()).thenReturn(debugger);
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getUriInfo()).thenReturn(uriInfo);
when(requestContext.getSerializer()).thenReturn(serializer);
when(requestContext.getTransactionFactory()).thenReturn(factory);
when(requestContext.getEtagHelper()).thenReturn(new JPAODataEtagHelperImpl(odata));
when(uriInfo.getUriResourceParts()).thenReturn(pathParts);
when(uriEts.getKeyPredicates()).thenReturn(keyPredicates);
when(uriEts.getEntitySet()).thenReturn(ets);
when(uriEts.getKind()).thenReturn(UriResourceKind.entitySet);
when(ets.getName()).thenReturn("Organizations");
when(factory.createTransaction()).thenReturn(transaction);
when(etsInfo.getEdmBindingTarget()).thenReturn(ets);
processor = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, convHelper);
}
protected ODataRequest prepareRepresentationRequest(final JPAAbstractCUDRequestHandler spy)
throws ODataException {
final ODataRequest request = prepareSimpleRequest("return=representation");
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
final Organization org = new Organization();
when(em.find(Organization.class, "35")).thenReturn(org);
org.setID("35");
final Edm edm = mock(Edm.class);
when(serviceMetadata.getEdm()).thenReturn(edm);
final EdmEntityType edmET = mock(EdmEntityType.class);
final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.Organization");
when(edm.getEntityType(fqn)).thenReturn(edmET);
final List<String> keyNames = new ArrayList<>();
keyNames.add("ID");
when(edmET.getKeyPredicateNames()).thenReturn(keyNames);
final EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class);
when(edmET.getKeyPropertyRef("ID")).thenReturn(refType);
when(edmET.getFullQualifiedName()).thenReturn(fqn);
final EdmProperty edmProperty = mock(EdmProperty.class);
when(refType.getProperty()).thenReturn(edmProperty);
when(refType.getName()).thenReturn("ID");
final EdmPrimitiveType type = mock(EdmPrimitiveType.class);
when(edmProperty.getType()).thenReturn(type);
when(type.toUriLiteral(ArgumentMatchers.any())).thenReturn("35");
when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(JPAEntityCollectionExtension.class)))
.thenReturn(
serializerResult);
when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ID\":\"35\"}".getBytes()));
return request;
}
protected ODataRequest prepareLinkRequest(final JPAAbstractCUDRequestHandler spy)
throws ODataException {
// .../AdministrativeDivisions(DivisionCode='DE60',CodeID='NUTS2',CodePublisher='Eurostat')
final ODataRequest request = prepareSimpleRequest("return=representation");
final Edm edm = mock(Edm.class);
final EdmEntityType edmET = mock(EdmEntityType.class);
final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision");
final List<String> keyNames = new ArrayList<>();
final AdministrativeDivisionKey key = new AdministrativeDivisionKey("Eurostat", "NUTS2", "DE60");
final AdministrativeDivision div = new AdministrativeDivision(key);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(em.find(AdministrativeDivision.class, key)).thenReturn(div);
when(serviceMetadata.getEdm()).thenReturn(edm);
when(edm.getEntityType(fqn)).thenReturn(edmET);
when(ets.getName()).thenReturn("AdministrativeDivisions");
when(uriEts.getKeyPredicates()).thenReturn(keyPredicates);
keyNames.add("DivisionCode");
keyNames.add("CodeID");
keyNames.add("CodePublisher");
when(edmET.getKeyPredicateNames()).thenReturn(keyNames);
when(edmET.getFullQualifiedName()).thenReturn(fqn);
final EdmPrimitiveType type = EdmString.getInstance();
EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class);
EdmProperty edmProperty = mock(EdmProperty.class);
when(edmET.getKeyPropertyRef("DivisionCode")).thenReturn(refType);
when(refType.getProperty()).thenReturn(edmProperty);
when(refType.getName()).thenReturn("DivisionCode");
when(edmProperty.getType()).thenReturn(type);
when(edmProperty.getMaxLength()).thenReturn(50);
refType = mock(EdmKeyPropertyRef.class);
edmProperty = mock(EdmProperty.class);
when(edmET.getKeyPropertyRef("CodeID")).thenReturn(refType);
when(refType.getProperty()).thenReturn(edmProperty);
when(refType.getName()).thenReturn("CodeID");
when(edmProperty.getType()).thenReturn(type);
when(edmProperty.getMaxLength()).thenReturn(50);
refType = mock(EdmKeyPropertyRef.class);
edmProperty = mock(EdmProperty.class);
when(edmET.getKeyPropertyRef("CodePublisher")).thenReturn(refType);
when(refType.getProperty()).thenReturn(edmProperty);
when(refType.getName()).thenReturn("CodePublisher");
when(edmProperty.getType()).thenReturn(type);
when(edmProperty.getMaxLength()).thenReturn(50);
when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(JPAEntityCollectionExtension.class)))
.thenReturn(
serializerResult);
when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ParentCodeID\":\"NUTS1\"}".getBytes()));
return request;
}
protected ODataRequest prepareSimpleRequest() throws ODataException {
return prepareSimpleRequest("return=minimal");
}
@SuppressWarnings("unchecked")
protected ODataRequest prepareSimpleRequest(final String content) throws ODataException {
final EntityTransaction transaction = mock(EntityTransaction.class);
when(em.getTransaction()).thenReturn(transaction);
final ODataRequest request = mock(ODataRequest.class);
when(request.getHeaders(HttpHeader.PREFER)).thenReturn(header);
when(requestContext.getEdmProvider()).thenReturn(jpaEdm);
when(etsInfo.getEdmBindingTarget()).thenReturn(ets);
header.add(content);
final Entity odataEntity = mock(Entity.class);
when(convHelper.convertInputStream(same(odata), same(request), same(ContentType.JSON), any(List.class)))
.thenReturn(odataEntity);
when(convHelper.convertKeyToLocal(ArgumentMatchers.eq(odata), ArgumentMatchers.eq(request), ArgumentMatchers.eq(
ets), ArgumentMatchers.any(JPAEntityType.class), ArgumentMatchers.any())).thenReturn(LOCATION_HEADER);
return request;
}
protected ODataRequest preparePersonRequest(final JPAAbstractCUDRequestHandler spy)
throws ODataException {
final ODataRequest request = prepareSimpleRequest("return=representation");
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
final Person person = new Person();
when(em.find(Person.class, "35")).thenReturn(person);
person.setID("35");
final Edm edm = mock(Edm.class);
when(serviceMetadata.getEdm()).thenReturn(edm);
final EdmEntityType edmET = mock(EdmEntityType.class);
final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.Person");
when(edm.getEntityType(fqn)).thenReturn(edmET);
final List<String> keyNames = new ArrayList<>();
keyNames.add("ID");
when(edmET.getKeyPredicateNames()).thenReturn(keyNames);
final EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class);
when(edmET.getKeyPropertyRef("ID")).thenReturn(refType);
when(edmET.getFullQualifiedName()).thenReturn(fqn);
final EdmProperty edmProperty = mock(EdmProperty.class);
when(refType.getProperty()).thenReturn(edmProperty);
when(refType.getName()).thenReturn("ID");
final EdmPrimitiveType type = mock(EdmPrimitiveType.class);
when(edmProperty.getType()).thenReturn(type);
when(type.toUriLiteral(ArgumentMatchers.any())).thenReturn("35");
when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(JPAEntityCollectionExtension.class)))
.thenReturn(
serializerResult);
when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ID\":\"35\"}".getBytes()));
return request;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAModifyUtilTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAModifyUtilTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAInvocationTargetException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole;
import com.sap.olingo.jpa.processor.core.testmodel.Country;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData;
import com.sap.olingo.jpa.processor.core.testobjects.BusinessPartnerRoleWithoutSetter;
import com.sap.olingo.jpa.processor.core.testobjects.OrganizationWithoutGetter;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
class JPAModifyUtilTest extends TestBase {
private JPAModifyUtil cut;
private Map<String, Object> jpaAttributes;
private BusinessPartner partner;
private JPAEntityType org;
@BeforeEach
void setUp() throws ODataException {
cut = new JPAModifyUtil();
jpaAttributes = new HashMap<>();
partner = new Organization();
helper = new TestHelper(emf, PUNIT_NAME);
org = helper.getJPAEntityType(Organization.class);
}
@Test
void testBuildMethodNameSuffix() throws ODataJPAModelException {
assertEquals("CreationDateTime", cut.buildMethodNameSuffix(org.getAttribute("creationDateTime").get()));
}
@Test
void testSetterName() throws ODataJPAModelException {
assertEquals("setCreationDateTime", cut.buildSetterName(org.getAttribute("creationDateTime").get()));
}
@Test
void testSetAttributeOneAttribute() throws ODataJPAProcessException {
jpaAttributes.put("iD", "Willi");
cut.setAttributes(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
}
@Test
void testSetAttributeMultipleAttribute() throws ODataJPAProcessException {
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("type", "2");
cut.setAttributes(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertEquals("2", partner.getType());
}
@Test
void testSetAttributeIfAttributeNull() throws ODataJPAProcessException {
partner.setType("2");
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("type", null);
cut.setAttributes(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertNull(partner.getType());
}
@Test
void testDoNotSetAttributeIfNotInMap() throws ODataJPAProcessException {
partner.setType("2");
jpaAttributes.put("iD", "Willi");
cut.setAttributes(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertEquals("2", partner.getType());
}
@Test
void testSetAttributesDeepOneAttribute() throws ODataJPAProcessException {
jpaAttributes.put("iD", "Willi");
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
}
@Test
void testSetAttributesDeepMultipleAttribute() throws ODataJPAProcessException {
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("country", "DEU");
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertEquals("DEU", partner.getCountry());
}
@Test
void testSetAttributeDeepIfAttributeNull() throws ODataJPAProcessException {
partner.setType("2");
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("type", null);
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertNull(partner.getType());
}
@Test
void testDoNotSetAttributeDeepIfNotInMap() throws ODataJPAProcessException {
partner.setType("2");
jpaAttributes.put("iD", "Willi");
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertEquals("2", partner.getType());
}
@Test
void testSetAttributesDeepShallIgnoreRequestEntities() throws ODataJPAProcessException {
try {
final JPARequestEntity roles = mock(JPARequestEntity.class);
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("roles", roles);
cut.setAttributesDeep(jpaAttributes, partner, org);
} catch (final Exception e) {
fail();
}
}
@Test
void testSetAttributesDeepOneLevelViaGetter() throws ODataJPAProcessException {
final Map<String, Object> embeddedAttributes = new HashMap<>();
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("address", embeddedAttributes);
embeddedAttributes.put("cityName", "Test Town");
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertNotNull(partner.getAddress());
assertEquals("Test Town", partner.getAddress().getCityName());
}
@Test
void testSetAttributesDeepOneLevelViaGetterWithWrongRequestData() throws Throwable {
final Map<String, Object> embeddedAttributes = new HashMap<>();
final Map<String, Object> innerEmbeddedAttributes = new HashMap<>();
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("administrativeInformation", embeddedAttributes);
embeddedAttributes.put("updated", innerEmbeddedAttributes);
innerEmbeddedAttributes.put("by", null);
try {
cut.setAttributesDeep(jpaAttributes, partner, org);
} catch (final ODataJPAInvocationTargetException e) {
assertEquals("Organization/AdministrativeInformation/Updated/By", e.getPath());
assertEquals(NullPointerException.class, e.getCause().getClass());
}
}
@Test
void testDoNotSetAttributesDeepOneLevelIfNotProvided() throws ODataJPAProcessException {
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("address", null);
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertNull(partner.getAddress());
}
@Test
void testSetAttributesDeepOneLevelIfNull() throws ODataJPAProcessException {
final PostalAddressData address = new PostalAddressData();
address.setCityName("Test City");
partner.setAddress(address);
jpaAttributes.put("iD", "Willi");
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertNotNull(partner.getAddress());
assertEquals("Test City", partner.getAddress().getCityName());
}
@Test
void testSetAttributesDeepOneLevelViaSetter() throws ODataJPAProcessException {
final Map<String, Object> embeddedAttributes = new HashMap<>();
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("communicationData", embeddedAttributes);
embeddedAttributes.put("email", "Test@Town");
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertNotNull(partner.getCommunicationData());
assertEquals("Test@Town", partner.getCommunicationData().getEmail());
}
@Test
void testSetAttributesDeepTwoLevel() throws ODataJPAProcessException {
final Map<String, Object> embeddedAttributes = new HashMap<>();
final Map<String, Object> innerEmbeddedAttributes = new HashMap<>();
jpaAttributes.put("iD", "Willi");
jpaAttributes.put("administrativeInformation", embeddedAttributes);
embeddedAttributes.put("updated", innerEmbeddedAttributes);
innerEmbeddedAttributes.put("by", "Hugo");
cut.setAttributesDeep(jpaAttributes, partner, org);
assertEquals("Willi", partner.getID());
assertNotNull(partner.getAdministrativeInformation());
assertNotNull(partner.getAdministrativeInformation().getUpdated());
assertEquals("Hugo", partner.getAdministrativeInformation().getUpdated().getBy());
}
@Test
void testCreatePrimaryKeyOneStringKeyField() throws ODataJPAProcessException, ODataJPAModelException {
final JPAEntityType et = createSingleKeyEntityType();
doReturn(String.class).when(et).getKeyType();
jpaAttributes.put("iD", "Willi");
final String act = (String) cut.createPrimaryKey(et, jpaAttributes, org);
assertEquals("Willi", act);
}
@Test
void testCreatePrimaryKeyOneIntegerKeyField() throws ODataJPAProcessException, ODataJPAModelException {
final JPAEntityType et = createSingleKeyEntityType();
doReturn(Integer.class).when(et).getKeyType();
jpaAttributes.put("iD", Integer.valueOf(10));
final Integer act = (Integer) cut.createPrimaryKey(et, jpaAttributes, org);
assertEquals(Integer.valueOf(10), act);
}
@Test
void testCreatePrimaryKeyOneBigIntegerKeyField() throws ODataJPAProcessException, ODataJPAModelException {
final JPAEntityType et = createSingleKeyEntityType();
doReturn(BigInteger.class).when(et).getKeyType();
jpaAttributes.put("iD", new BigInteger("10"));
final BigInteger act = (BigInteger) cut.createPrimaryKey(et, jpaAttributes, org);
assertEquals(new BigInteger("10"), act);
}
@Test
void testCreatePrimaryKeyMultipleField() throws ODataJPAProcessException {
final JPAEntityType et = mock(JPAEntityType.class);
doReturn(AdministrativeDivisionKey.class).when(et).getKeyType();
jpaAttributes.put("codePublisher", "Test");
jpaAttributes.put("codeID", "10");
jpaAttributes.put("divisionCode", "10.1");
final AdministrativeDivisionKey act = (AdministrativeDivisionKey) cut.createPrimaryKey(et, jpaAttributes, org);
assertEquals("Test", act.getCodePublisher());
assertEquals("10", act.getCodeID());
assertEquals("10.1", act.getDivisionCode());
}
@Test
void testDeepLinkComplexNotExist() throws ODataJPAProcessorException, ODataJPAModelException {
final Organization source = new Organization("100");
final Person target = new Person();
target.setID("A");
final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations",
"AdministrativeInformation/Updated/User");
cut.linkEntities(source, target, path);
assertNotNull(source.getAdministrativeInformation());
assertNotNull(source.getAdministrativeInformation().getUpdated());
assertEquals(target, source.getAdministrativeInformation().getUpdated().getUser());
}
@Test
void testSetPrimitiveKeyString() throws ODataJPAModelException, ODataJPAProcessorException {
final var et = helper.getJPAEntityType(Person.class);
final var act = new Person();
jpaAttributes.put("iD", "10");
cut.setPrimaryKey(et, jpaAttributes, act);
assertEquals("10", act.getID());
}
@Test
void testSetCompoundKeyString() throws ODataJPAModelException, ODataJPAProcessorException {
final var et = helper.getJPAEntityType(AdministrativeDivision.class);
final var act = new AdministrativeDivision();
jpaAttributes.put("codePublisher", "Test");
jpaAttributes.put("codeID", "10");
jpaAttributes.put("divisionCode", "10.1");
cut.setPrimaryKey(et, jpaAttributes, act);
assertEquals("Test", act.getCodePublisher());
assertEquals("10", act.getCodeID());
assertEquals("10.1", act.getDivisionCode());
}
@Test
void testSetEmbeddedKeyString() throws ODataJPAModelException, ODataJPAProcessorException {
final var et = helper.getJPAEntityType(AdministrativeDivisionDescription.class);
final var act = new AdministrativeDivisionDescription();
jpaAttributes.put("codePublisher", "Test");
jpaAttributes.put("codeID", "10");
jpaAttributes.put("divisionCode", "10.1");
jpaAttributes.put("language", "DE");
cut.setPrimaryKey(et, jpaAttributes, act);
final var key = act.getKey();
assertEquals("Test", key.getCodePublisher());
assertEquals("10", key.getCodeID());
assertEquals("10.1", key.getDivisionCode());
assertEquals("DE", key.getLanguage());
}
@Test
void testDirectLink() throws ODataJPAProcessorException, ODataJPAModelException {
final Organization source = new Organization("100");
final BusinessPartnerRole target = new BusinessPartnerRole();
target.setBusinessPartnerID("100");
target.setRoleCategory("A");
final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations",
"Roles");
cut.linkEntities(source, target, path);
assertNotNull(source.getRoles());
assertNotNull(source.getRoles().toArray()[0]);
assertEquals(target, source.getRoles().toArray()[0]);
}
@Test
void testSetForeignKeyOneKey() throws ODataJPAModelException, ODataJPAProcessorException {
final Organization source = new Organization("100");
final BusinessPartnerRole target = new BusinessPartnerRole();
target.setRoleCategory("A");
final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations",
"Roles");
cut.setForeignKey(source, target, path);
assertEquals("100", target.getBusinessPartnerID());
}
@Test
void testSetForeignKeyThrowsExceptionOnMissingGetter() throws ODataJPAModelException {
final OrganizationWithoutGetter source = new OrganizationWithoutGetter("100");
final BusinessPartnerRole target = new BusinessPartnerRole();
target.setRoleCategory("A");
final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations",
"Roles");
assertThrows(ODataJPAProcessorException.class, () -> {
cut.setForeignKey(source, target, path);
});
}
@Test
void testSetForeignKeyThrowsExceptionOnMissingSetter() throws ODataJPAModelException {
final Organization source = new Organization("100");
final BusinessPartnerRoleWithoutSetter target = new BusinessPartnerRoleWithoutSetter();
final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations",
"Roles");
assertThrows(ODataJPAProcessorException.class, () -> {
cut.setForeignKey(source, target, path);
});
}
@Test
void testBuildSetterList() throws ODataJPAModelException {
final List<JPAAttribute> attributes = Arrays.asList(org.getAttribute("creationDateTime").get(),
org.getAttribute("country").get());
final Map<JPAAttribute, Method> act = cut.buildSetterList(org.getTypeClass(), attributes);
assertEquals(2, act.size());
assertNotNull(act.get(org.getAttribute("creationDateTime").get()));
assertNotNull(act.get(org.getAttribute("country").get()));
assertEquals(LocalDateTime.class, act.get(org.getAttribute("creationDateTime").get()).getParameterTypes()[0]);
}
@Test
void testBuildSetterListContainsNullIfForMissingSetter() throws ODataJPAModelException {
final JPAEntityType country = helper.getJPAEntityType(Country.class);
final List<JPAAttribute> attributes = Arrays.asList(country.getAttribute("code").get(),
country.getAttribute("name").get());
final Map<JPAAttribute, Method> act = cut.buildSetterList(country.getTypeClass(), attributes);
assertEquals(2, act.size());
assertNotNull(act.get(country.getAttribute("code").get()));
assertNull(act.get(country.getAttribute("name").get()));
assertEquals(String.class, act.get(country.getAttribute("code").get()).getParameterTypes()[0]);
}
private JPAEntityType createSingleKeyEntityType() throws ODataJPAModelException {
final List<JPAAttribute> keyAttributes = new ArrayList<>();
final JPAAttribute keyAttribute = mock(JPAAttribute.class);
final JPAEntityType et = mock(JPAEntityType.class);
when(keyAttribute.getInternalName()).thenReturn("iD");
keyAttributes.add(keyAttribute);
when(et.getKey()).thenReturn(keyAttributes);
return et;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataInternalRequestContextTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataInternalRequestContextTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.debug.DebugSupport;
import org.apache.olingo.server.api.etag.ETagHelper;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmQueryExtensionProvider;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmTransientPropertyCalculator;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAQueryExtension;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataApiVersionAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataDefaultTransactionFactory;
import com.sap.olingo.jpa.processor.core.api.JPAODataEtagHelper;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataPathInformation;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives.UuidSortOrder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.errormodel.DummyPropertyCalculator;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
import com.sap.olingo.jpa.processor.core.testmodel.CurrentUserQueryExtension;
class JPAODataInternalRequestContextTest {
private JPAODataInternalRequestContext cut;
private JPAODataRequestContextAccess contextAccess;
private JPAODataRequestContext requestContext;
private JPAODataSessionContextAccess sessionContext;
private Map<String, List<String>> header;
private JPASerializer serializer;
private JPAODataTransactionFactory transactionFactory;
private JPARequestParameterMap customParameter;
private UriInfo uriInfo;
private EntityManager em;
private Optional<JPAODataClaimProvider> claims;
private Optional<JPAODataGroupProvider> groups;
private JPAServiceDebugger debugger;
private List<Locale> locales;
private UriInfoResource uriInfoResource;
private JPACUDRequestHandler cudHandler;
private DebugSupport debugSupport;
private JPAODataDatabaseProcessor dbProcessor;
private JPAEdmProvider edmProvider;
private JPAODataDatabaseOperations operationConverter;
private JPAODataQueryDirectives queryDirectives;
private JPAODataEtagHelper etagHelper;
private JPAODataPagingProvider pagingProvider;
private OData odata;
private ETagHelper olingoEtagHelper;
private JPAODataPathInformation pathInformation;
private JPAODataApiVersionAccess version;
@BeforeEach
void setup() {
contextAccess = mock(JPAODataRequestContextAccess.class);
requestContext = mock(JPAODataRequestContext.class);
sessionContext = mock(JPAODataSessionContextAccess.class);
version = mock(JPAODataApiVersionAccess.class);
odata = mock(OData.class);
olingoEtagHelper = mock(ETagHelper.class);
uriInfoResource = mock(UriInfoResource.class);
header = new HashMap<>();
customParameter = mock(JPARequestParameterMap.class);
transactionFactory = mock(JPAODataTransactionFactory.class);
uriInfo = mock(UriInfo.class);
em = mock(EntityManager.class);
claims = Optional.empty();
groups = Optional.empty();
debugger = mock(JPAServiceDebugger.class);
locales = new LinkedList<>();
cudHandler = mock(JPACUDRequestHandler.class);
debugSupport = mock(DebugSupport.class);
dbProcessor = mock(JPAODataDatabaseProcessor.class);
edmProvider = mock(JPAEdmProvider.class);
operationConverter = mock(JPAODataDatabaseOperations.class);
queryDirectives = new JPAODataQueryDirectives.JPAODataQueryDirectivesImpl(0, UuidSortOrder.AS_STRING);
pagingProvider = mock(JPAODataPagingProvider.class);
etagHelper = mock(JPAODataEtagHelper.class);
pathInformation = new JPAODataPathInformation("", "", "", "");
when(odata.createETagHelper()).thenReturn(olingoEtagHelper);
when(contextAccess.getTransactionFactory()).thenReturn(transactionFactory);
when(contextAccess.getRequestParameter()).thenReturn(customParameter);
when(contextAccess.getEntityManager()).thenReturn(em);
when(contextAccess.getClaimsProvider()).thenReturn(claims);
when(contextAccess.getGroupsProvider()).thenReturn(groups);
when(contextAccess.getProvidedLocale()).thenReturn(locales);
when(contextAccess.getDebugger()).thenReturn(debugger);
when(contextAccess.getQueryDirectives()).thenReturn(queryDirectives);
when(contextAccess.getEtagHelper()).thenReturn(etagHelper);
when(contextAccess.getPagingProvider()).thenReturn(Optional.of(pagingProvider));
when(contextAccess.getPathInformation()).thenReturn(pathInformation);
when(requestContext.getClaimsProvider()).thenReturn(claims);
when(requestContext.getCUDRequestHandler()).thenReturn(cudHandler);
when(requestContext.getGroupsProvider()).thenReturn(groups);
when(requestContext.getTransactionFactory()).thenReturn(transactionFactory);
when(requestContext.getRequestParameter()).thenReturn(customParameter);
when(requestContext.getLocales()).thenReturn(locales);
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getDebuggerSupport()).thenReturn(debugSupport);
when(requestContext.getVersion()).thenReturn(JPAODataApiVersionAccess.DEFAULT_VERSION);
when(debugSupport.isUserAuthorized()).thenReturn(Boolean.TRUE);
when(version.getId()).thenReturn(JPAODataApiVersionAccess.DEFAULT_VERSION);
when(version.getEdmProvider()).thenReturn(edmProvider);
when(sessionContext.getDatabaseProcessor()).thenReturn(dbProcessor);
when(sessionContext.getOperationConverter()).thenReturn(operationConverter);
when(sessionContext.getQueryDirectives()).thenReturn(queryDirectives);
when(sessionContext.getPagingProvider()).thenReturn(pagingProvider);
when(sessionContext.getApiVersion(anyString())).thenReturn(version);
}
@Test
void testCreateFromContextUriAccessWithDebugger() throws ODataJPAProcessorException {
cut = new JPAODataInternalRequestContext(uriInfoResource, serializer, contextAccess, header, pathInformation);
assertEquals(transactionFactory, cut.getTransactionFactory());
assertEquals(serializer, cut.getSerializer());
assertEquals(header, cut.getHeader());
assertNotEquals(customParameter, cut.getRequestParameter());
assertEquals(uriInfoResource, cut.getUriInfo());
assertEquals(em, cut.getEntityManager());
assertEquals(claims, cut.getClaimsProvider());
assertEquals(groups, cut.getGroupsProvider());
assertTrue(cut.getDebugger() instanceof JPAEmptyDebugger);
assertEquals(locales, cut.getProvidedLocale());
assertNotNull(cut.getCUDRequestHandler());
assertEquals(queryDirectives, cut.getQueryDirectives());
assertEquals(etagHelper, cut.getEtagHelper());
assertEquals(pagingProvider, cut.getPagingProvider().get());
assertEquals(pathInformation, cut.getPathInformation());
}
@Test
void testCreateFromContextUriContextAccess() throws ODataJPAProcessorException {
when(contextAccess.getHeader()).thenReturn(new JPAHttpHeaderHashMap(header));
cut = new JPAODataInternalRequestContext(uriInfoResource, contextAccess);
assertEquals(transactionFactory, cut.getTransactionFactory());
assertEquals(serializer, cut.getSerializer());
assertEquals(header, cut.getHeader());
assertNotEquals(customParameter, cut.getRequestParameter());
assertEquals(uriInfoResource, cut.getUriInfo());
assertEquals(em, cut.getEntityManager());
assertEquals(claims, cut.getClaimsProvider());
assertEquals(groups, cut.getGroupsProvider());
assertTrue(cut.getDebugger() instanceof JPAEmptyDebugger);
assertEquals(locales, cut.getProvidedLocale());
assertNotNull(cut.getCUDRequestHandler());
assertEquals(queryDirectives, cut.getQueryDirectives());
assertEquals(etagHelper, cut.getEtagHelper());
assertEquals(pagingProvider, cut.getPagingProvider().get());
assertEquals(pathInformation, cut.getPathInformation());
}
@Test
void testCreateFromContextUriContextAccessHeader() throws ODataJPAProcessorException {
cut = new JPAODataInternalRequestContext(uriInfoResource, contextAccess, header);
assertEquals(transactionFactory, cut.getTransactionFactory());
assertEquals(serializer, cut.getSerializer());
assertEquals(header, cut.getHeader());
assertNotEquals(customParameter, cut.getRequestParameter());
assertEquals(uriInfoResource, cut.getUriInfo());
assertEquals(em, cut.getEntityManager());
assertEquals(claims, cut.getClaimsProvider());
assertEquals(groups, cut.getGroupsProvider());
assertTrue(cut.getDebugger() instanceof JPAEmptyDebugger);
assertEquals(locales, cut.getProvidedLocale());
assertNotNull(cut.getCUDRequestHandler());
assertEquals(queryDirectives, cut.getQueryDirectives());
assertEquals(etagHelper, cut.getEtagHelper());
assertEquals(pagingProvider, cut.getPagingProvider().get());
}
@Test
void testCreateFromRequestContextWithDebugSupport() {
// contextAccess.get
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertEquals(em, cut.getEntityManager());
assertEquals(claims, cut.getClaimsProvider());
assertEquals(groups, cut.getGroupsProvider());
assertEquals(cudHandler, cut.getCUDRequestHandler());
assertTrue(cut.getDebugSupport().isUserAuthorized());
assertEquals(transactionFactory, cut.getTransactionFactory());
assertEquals(locales, cut.getProvidedLocale());
assertEquals(customParameter, cut.getRequestParameter());
assertEquals(queryDirectives, cut.getQueryDirectives());
assertEquals(pagingProvider, cut.getPagingProvider().get());
}
@Test
void testCreateFromContextAccessWithDebugSupport() throws ODataJPAProcessorException {
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
cut = new JPAODataInternalRequestContext(uriInfo, serializer, cut, header, pathInformation);
assertTrue(cut.getDebugSupport().isUserAuthorized());
}
@Test
void testGetLocaleLocaleNotEmpty() throws ODataJPAProcessorException {
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
locales.add(Locale.JAPAN);
locales.add(Locale.CANADA_FRENCH);
assertEquals(Locale.JAPAN, cut.getLocale());
}
@Test
void testGetLocaleLocaleEmpty() throws ODataJPAProcessorException {
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
assertEquals(Locale.ENGLISH, cut.getLocale());
}
@Test
void testGetLocaleLocaleNull() throws ODataJPAProcessorException {
when(contextAccess.getProvidedLocale()).thenReturn(null);
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
assertEquals(Locale.ENGLISH, cut.getLocale());
}
@Test
void testGetTransactionFactoryIfNull() throws ODataJPAProcessorException {
when(contextAccess.getTransactionFactory()).thenReturn(null);
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
assertTrue(cut.getTransactionFactory() instanceof JPAODataDefaultTransactionFactory);
}
@Test
void testGetDebuggerReturnsDefaultIfNullAndFalse() throws ODataJPAProcessorException {
when(contextAccess.getDebugger()).thenReturn(null);
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
assertTrue(cut.getDebugger() instanceof JPAEmptyDebugger);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
void testGetQueryEnhancement() throws ODataJPAModelException, ODataJPAProcessorException {
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
final JPAEntityType et = mock(JPAEntityType.class);
final JPAQueryExtension extension = mock(JPAQueryExtension.class);
when(et.getQueryExtension()).thenReturn(Optional.of(extension));
when(extension.getConstructor()).thenAnswer(new Answer<Constructor<? extends EdmQueryExtensionProvider>>() {
@Override
public Constructor<? extends EdmQueryExtensionProvider> answer(final InvocationOnMock invocation)
throws Throwable {
return (Constructor<? extends EdmQueryExtensionProvider>) CurrentUserQueryExtension.class
.getConstructors()[0];
}
});
assertTrue(cut.getQueryEnhancement(et).isPresent());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculator() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> constructor = DummyPropertyCalculator.class.getConstructor(EntityManager.class);
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) constructor);
assertTrue(cut.getCalculator(attribute).isPresent());
}
@Test
void testSetUriInfoThrowsExceptionPageExists() throws ODataJPAProcessorException {
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
assertThrows(ODataJPAIllegalAccessException.class, () -> cut.setUriInfo(uriInfo));
}
@Test
void testSetSerializer() throws ODataJPAProcessorException {
final JPASerializer jpaSerializer = mock(JPASerializer.class);
cut = new JPAODataInternalRequestContext(uriInfo, serializer, contextAccess, header, pathInformation);
cut.setJPASerializer(jpaSerializer);
assertEquals(jpaSerializer, cut.getSerializer());
}
@Test
void testGetDatabaseProcessor() {
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertEquals(dbProcessor, cut.getDatabaseProcessor());
}
@Test
void testGetEdmProvider() throws ODataException {
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertEquals(edmProvider, cut.getEdmProvider());
}
@Test
void testGetEdmProviderRestricted() throws ODataException {
final var groupsProvider = mock(JPAODataGroupProvider.class);
final List<String> groupList = List.of("Company");
final var restrictedProvider = mock(JPAEdmProvider.class);
when(requestContext.getGroupsProvider()).thenReturn(Optional.of(groupsProvider));
when(groupsProvider.getGroups()).thenReturn(groupList);
when(edmProvider.asUserGroupRestricted(groupList)).thenReturn(restrictedProvider);
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertEquals(restrictedProvider, cut.getEdmProvider());
}
@Test
void testGetOperationConverter() {
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertEquals(operationConverter, cut.getOperationConverter());
}
@Test
void testGetEtagHelper() {
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertNotNull(cut.getEtagHelper());
}
@Test
void testTakesVersion() throws ODataJPAProcessorException {
final var emf = mock(EntityManagerFactory.class);
when(emf.createEntityManager()).thenReturn(em);
when(requestContext.getEntityManager()).thenReturn(null);
when(requestContext.getVersion()).thenReturn("V10");
when(version.getId()).thenReturn("V10");
when(version.getEdmProvider()).thenReturn(edmProvider);
when(version.getEntityManagerFactory()).thenReturn(emf);
when(sessionContext.getApiVersion("V10")).thenReturn(version);
when(sessionContext.getApiVersion(JPAODataApiVersionAccess.DEFAULT_VERSION)).thenReturn(null);
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertNotNull(cut.getEdmProvider());
assertNotNull(cut.getEntityManager());
}
@Test
void testGetMappingPathNullIfNotProvided() {
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertNull(cut.getMappingPath());
}
@Test
void testGetMappingPathReturnsProvided() {
when(version.getMappingPath()).thenReturn("test/v1");
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
assertEquals("test/v1", cut.getMappingPath());
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAFunctionRequestProcessorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAFunctionRequestProcessorTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
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.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.olingo.commons.api.data.Annotatable;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmParameter;
import org.apache.olingo.commons.api.edm.EdmReturnType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.commons.core.edm.primitivetype.EdmBoolean;
import org.apache.olingo.commons.core.edm.primitivetype.EdmDate;
import org.apache.olingo.commons.core.edm.primitivetype.EdmInt16;
import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.deserializer.ODataDeserializer;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriHelper;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunctionType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJavaFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataEtagHelper;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionActionConstructor;
import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionReturnType;
class JPAFunctionRequestProcessorTest {
private JPAFunctionRequestProcessor cut;
private ContentType requestFormat;
@Mock
private ODataDeserializer deserializer;
@Mock
private JPAOperationSerializer serializer;
@Mock
private OData odata;
@Mock
private JPAODataRequestContextAccess requestContext;
@Mock
private ODataRequest request;
@Mock
private ODataResponse response;
@Mock
private JPAJavaFunction function;
@Mock
private JPAServiceDocument sd;
@Mock
private UriInfo uriInfo;
private List<UriResource> uriResources;
private List<UriParameter> uriParameters;
@Mock
private UriResourceFunction resource;
@Mock
private EdmFunction edmFunction;
@Captor
ArgumentCaptor<Annotatable> annotatableCaptor;
@Mock
private UriHelper uriHelper;
@Mock
private JPAODataEtagHelper etagHelper;
@BeforeEach
void setup() throws ODataException {
MockitoAnnotations.openMocks(this);
uriResources = new ArrayList<>();
uriResources.add(resource);
uriParameters = new ArrayList<>();
final EntityManager em = mock(EntityManager.class);
final CriteriaBuilder cb = mock(CriteriaBuilder.class);
final JPAEdmProvider edmProvider = mock(JPAEdmProvider.class);
final SerializerResult serializerResult = mock(SerializerResult.class);
when(requestContext.getEntityManager()).thenReturn(em);
when(em.getCriteriaBuilder()).thenReturn(cb);
when(requestContext.getEdmProvider()).thenReturn(edmProvider);
when(edmProvider.getServiceDocument()).thenReturn(sd);
when(requestContext.getRequestParameter()).thenReturn(new JPARequestParameterHashMap());
when(requestContext.getHeader()).thenReturn(new JPAHttpHeaderHashMap());
when(requestContext.getUriInfo()).thenReturn(uriInfo);
when(requestContext.getSerializer()).thenReturn(serializer);
when(requestContext.getEtagHelper()).thenReturn(etagHelper);
when(serializer.serialize(any(Annotatable.class), any(EdmType.class), any(ODataRequest.class)))
.thenReturn(serializerResult);
when(serializer.getContentType()).thenReturn(ContentType.APPLICATION_JSON);
when(uriInfo.getUriResourceParts()).thenReturn(uriResources);
when(resource.getFunction()).thenReturn(edmFunction);
when(resource.getParameters()).thenReturn(uriParameters);
when(edmFunction.isBound()).thenReturn(Boolean.FALSE);
when(function.getFunctionType()).thenReturn(EdmFunctionType.JavaClass);
when(sd.getFunction(edmFunction)).thenReturn(function);
when(odata.createDeserializer((ContentType) any())).thenReturn(deserializer);
when(odata.createUriHelper()).thenReturn(uriHelper);
requestFormat = ContentType.APPLICATION_JSON;
cut = new JPAFunctionRequestProcessor(odata, requestContext);
}
@Test
void testCallsWithParameterValue() throws IllegalArgumentException, NoSuchMethodException,
SecurityException, ODataApplicationException, ODataLibraryException, ODataJPAModelException {
final Method method = setConstructorAndMethod("primitiveValue", short.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter =
createParameter("A", "5", Short.class, method);
final EdmReturnType returnType = mock(EdmReturnType.class);
when(returnType.getType()).thenReturn(EdmInt32.getInstance());
when(edmFunction.getReturnType()).thenReturn(returnType);
when(edmFunction.getParameter("A")).thenReturn(parameter.getMiddle());
final JPAOperationResultParameter resultParameter = mock(JPAOperationResultParameter.class);
when(function.getResultParameter()).thenReturn(resultParameter);
when(resultParameter.isCollection()).thenReturn(Boolean.FALSE);
cut.retrieveData(request, response, requestFormat);
verify(response).setStatusCode(HttpStatusCode.OK.getStatusCode());
verify(serializer).serialize(annotatableCaptor.capture(), eq(EdmInt32.getInstance()), eq(request));
assertTrue(annotatableCaptor.getValue().toString().contains("5"));
}
@Test
void testCallsWithParameterNull() throws NoSuchMethodException, ODataJPAModelException, ODataApplicationException,
ODataLibraryException {
final Method method = setConstructorAndMethod("primitiveValueNullable", Short.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter =
createParameter("A", null, Short.class, method);
final EdmReturnType returnType = mock(EdmReturnType.class);
when(returnType.getType()).thenReturn(EdmInt32.getInstance());
when(edmFunction.getReturnType()).thenReturn(returnType);
when(edmFunction.getParameter("A")).thenReturn(parameter.getMiddle());
final JPAOperationResultParameter resultParameter = mock(JPAOperationResultParameter.class);
when(function.getResultParameter()).thenReturn(resultParameter);
when(resultParameter.isCollection()).thenReturn(Boolean.FALSE);
cut.retrieveData(request, response, requestFormat);
verify(response).setStatusCode(HttpStatusCode.OK.getStatusCode());
verify(serializer).serialize(annotatableCaptor.capture(), eq(EdmInt32.getInstance()), eq(request));
assertTrue(annotatableCaptor.getValue().toString().contains("0"));
}
@Test
void testCallsWithConstructorParameterValue() throws NoSuchMethodException, ODataJPAModelException,
ODataApplicationException, ODataLibraryException {
final Method method = setConstructorAndMethod(TestFunctionActionConstructor.class, "func", LocalDate.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter =
createParameter("date", "2024-10-03", LocalDate.class, method);
final EdmReturnType returnType = mock(EdmReturnType.class);
when(returnType.getType()).thenReturn(EdmBoolean.getInstance());
when(edmFunction.getReturnType()).thenReturn(returnType);
when(edmFunction.getParameter("date")).thenReturn(parameter.getMiddle());
final JPAOperationResultParameter resultParameter = mock(JPAOperationResultParameter.class);
when(function.getResultParameter()).thenReturn(resultParameter);
when(resultParameter.isCollection()).thenReturn(Boolean.FALSE);
cut.retrieveData(request, response, requestFormat);
verify(response).setStatusCode(HttpStatusCode.OK.getStatusCode());
verify(serializer).serialize(annotatableCaptor.capture(), eq(EdmBoolean.getInstance()), eq(request));
assertTrue(annotatableCaptor.getValue().toString().contains("true"));
}
@Test
void testEtagHeaderFilledForEntity() throws NoSuchMethodException, ODataApplicationException, ODataLibraryException,
ODataJPAModelException {
setConstructorAndMethod(TestFunctionReturnType.class, "convertBirthday");
final EdmReturnType returnType = mock(EdmReturnType.class);
final EdmEntityType type = mock(EdmEntityType.class);
when(returnType.getType()).thenReturn(type);
when(edmFunction.getReturnType()).thenReturn(returnType);
when(type.getKind()).thenReturn(EdmTypeKind.ENTITY);
final JPAOperationResultParameter resultParameter = mock(JPAOperationResultParameter.class);
when(function.getResultParameter()).thenReturn(resultParameter);
when(resultParameter.isCollection()).thenReturn(Boolean.FALSE);
final JPAEntityType jpaType = mock(JPAEntityType.class);
final JPAAttribute idAttribute = createJPAAttribute("iD", "Test", "ID");
final JPAAttribute etagAttribute = createJPAAttribute("eTag", "Test", "ETag");
final List<JPAAttribute> attributes = Arrays.asList(idAttribute, etagAttribute);
final JPAPath etagPath = mock(JPAPath.class);
final JPAElement pathPart = mock(JPAElement.class);
when(sd.getEntity(type)).thenReturn(jpaType);
when(jpaType.getExternalFQN()).thenReturn(new FullQualifiedName("Test", "Person"));
doReturn(Person.class).when(jpaType).getTypeClass();
when(jpaType.getAttributes()).thenReturn(attributes);
when(jpaType.hasEtag()).thenReturn(true);
when(jpaType.getEtagPath()).thenReturn(etagPath);
when(etagPath.getPath()).thenReturn(Arrays.asList(pathPart));
when(pathPart.getInternalName()).thenReturn("eTag");
when(etagHelper.asEtag(any(), any())).thenReturn("\"3\"");
when(uriHelper.buildKeyPredicate(any(), any())).thenReturn("example.org");
cut.retrieveData(request, response, requestFormat);
verify(response, times(1)).setStatusCode(200);
verify(response, times(1)).setHeader(HttpHeader.ETAG, "\"3\"");
}
private Method setConstructorAndMethod(final String methodName,
final Class<?>... parameterTypes) throws NoSuchMethodException {
return setConstructorAndMethod(TestFunctionReturnType.class, methodName, parameterTypes);
}
private JPAAttribute createJPAAttribute(final String internalName, final String namespace,
final String externalName) {
final JPAAttribute attribute = mock(JPAAttribute.class);
when(attribute.getInternalName()).thenReturn(internalName);
when(attribute.getExternalName()).thenReturn(externalName);
when(attribute.getExternalFQN()).thenReturn(new FullQualifiedName(namespace, externalName));
return attribute;
}
@SuppressWarnings("unchecked")
private Method setConstructorAndMethod(final Class<?> clazz, final String methodName,
final Class<?>... parameterTypes) throws NoSuchMethodException {
@SuppressWarnings("rawtypes")
final Constructor constructor = clazz.getConstructors()[0];
final Method method = clazz.getMethod(methodName, parameterTypes);
when(function.getConstructor()).thenReturn(constructor);
when(function.getMethod()).thenReturn(method);
when(function.getReturnType()).thenReturn(null);
return method;
}
private Triple<UriParameter, EdmParameter, JPAParameter> createParameter(final String name, final String value,
final Class<?> parameterType, final Method method) throws ODataJPAModelException {
final UriParameter uriParameter = mock(UriParameter.class);
when(uriParameter.getName()).thenReturn(name);
when(uriParameter.getText()).thenReturn(value);
uriParameters.add(uriParameter);
final JPAParameter parameter = mock(JPAParameter.class);
when(parameter.getName()).thenReturn(name);
doReturn(parameterType).when(parameter).getType();
when(function.getParameter(method.getParameters()[0])).thenReturn(parameter);
final EdmParameter edmParameter = mock(EdmParameter.class);
when(edmParameter.getType()).thenReturn(parameterType == LocalDate.class
? EdmDate.getInstance()
: EdmInt16.getInstance());
return new ImmutableTriple<>(uriParameter, edmParameter, parameter);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAClearProcessorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAClearProcessorTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
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.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.apache.olingo.server.api.uri.UriResourceValue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys;
import com.sap.olingo.jpa.processor.core.exception.ODataJPATransactionException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult;
class JPAClearProcessorTest extends TestJPAModifyProcessor {
private ODataRequest request;
@Override
@BeforeEach
public void setup() throws Exception {
super.setup();
request = mock(ODataRequest.class);
processor = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext,
new JPAConversionHelper());
}
@Test
void testSuccessReturnCode() throws ODataApplicationException {
// .../Organizations('35')/Name2
final ODataResponse response = new ODataResponse();
prepareDeleteName2();
processor.clearFields(request, response);
assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode());
}
@Test
void testHockIsCalled() throws ODataApplicationException {
// .../Organizations('35')/Name2
final RequestHandleSpy spy = prepareDeleteName2();
processor.clearFields(request, new ODataResponse());
assertTrue(spy.called);
}
@Test
void testHeadersProvided() throws ODataException {
final Map<String, List<String>> headers = new HashMap<>();
when(request.getAllHeaders()).thenReturn(headers);
headers.put("If-Match", Arrays.asList("2"));
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.clearFields(request, new ODataResponse());
assertNotNull(spy.headers);
assertEquals(1, spy.headers.size());
assertNotNull(spy.headers.get("If-Match"));
assertEquals("2", spy.headers.get("If-Match").get(0));
}
@Test
void testClaimsProvided() throws ODataException {
final ODataRequest otherRequest = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
final JPAODataClaimProvider provider = new JPAODataClaimsProvider();
final Optional<JPAODataClaimProvider> claims = Optional.of(provider);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(requestContext.getClaimsProvider()).thenReturn(claims);
processor.clearFields(otherRequest, new ODataResponse());
assertNotNull(spy.claims);
assertTrue(spy.claims.isPresent());
assertEquals(provider, spy.claims.get());
}
@Test
void testGroupsProvided() throws ODataException {
final ODataRequest otherRequest = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
final JPAODataGroupsProvider provider = new JPAODataGroupsProvider();
provider.addGroup("Person");
final Optional<JPAODataGroupProvider> groups = Optional.of(provider);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(requestContext.getGroupsProvider()).thenReturn(groups);
processor.clearFields(otherRequest, new ODataResponse());
assertNotNull(spy.groups);
assertFalse(spy.groups.isEmpty());
assertEquals("Person", spy.groups.get(0));
}
@Test
void testSimplePropertyEntityTypeProvided() throws ODataApplicationException {
// .../Organizations('35')/Name2
final RequestHandleSpy spy = prepareDeleteName2();
processor.clearFields(request, new ODataResponse());
assertEquals("Organization", spy.et.getExternalName());
}
@Test
void testSimplePropertyKeyProvided() throws ODataApplicationException {
// .../Organizations('35')/Name2
final RequestHandleSpy spy = prepareDeleteName2();
final List<UriParameter> keys = new ArrayList<>();
final UriParameter uriParam = mock(UriParameter.class);
when(uriParam.getText()).thenReturn("'35'");
when(uriParam.getName()).thenReturn("ID");
keys.add(uriParam);
when(uriEts.getKeyPredicates()).thenReturn(keys);
processor.clearFields(request, new ODataResponse());
assertEquals(1, spy.keyPredicates.size());
assertEquals("35", spy.keyPredicates.get("iD"));
}
@Test
void testSimplePropertyAttributeProvided() throws ODataApplicationException {
// .../Organizations('35')/Name2
final RequestHandleSpy spy = prepareDeleteName2();
processor.clearFields(request, new ODataResponse());
assertEquals(1, spy.jpaAttributes.size());
final Object[] keys = spy.jpaAttributes.keySet().toArray();
assertEquals("name2", keys[0].toString());
}
@Test
void testSimpleCollectionPropertyAttributeProvided() throws ODataApplicationException {
// .../Organizations('35')/Comment
final RequestHandleSpy spy = prepareDeleteComment();
processor.clearFields(request, new ODataResponse());
assertEquals(1, spy.jpaAttributes.size());
final Object[] keys = spy.jpaAttributes.keySet().toArray();
assertEquals("comment", keys[0].toString());
}
@Test
void testComplexPropertyHoleProvided() throws ODataApplicationException {
// .../Organizations('35')/Address
final RequestHandleSpy spy = prepareDeleteAddress();
processor.clearFields(request, new ODataResponse());
assertEquals(1, spy.jpaAttributes.size());
final Object[] keys = spy.jpaAttributes.keySet().toArray();
assertEquals("address", keys[0].toString());
}
@Test
void testSimplePropertyValueAttributeProvided() throws ODataApplicationException {
// .../Organizations('35')/Name2/$value
final RequestHandleSpy spy = prepareDeleteName2();
UriResourceValue uriProperty;
uriProperty = mock(UriResourceValue.class);
pathParts.add(uriProperty);
processor.clearFields(request, new ODataResponse());
assertEquals(1, spy.jpaAttributes.size());
final Object[] keys = spy.jpaAttributes.keySet().toArray();
assertEquals("name2", keys[0].toString());
}
@Test
void testComplexPropertyOnePropertyProvided() throws ODataApplicationException {
// .../Organizations('35')/Address/Country
final RequestHandleSpy spy = prepareDeleteAddressCountry();
processor.clearFields(request, new ODataResponse());
assertEquals(1, spy.jpaAttributes.size());
@SuppressWarnings("unchecked")
final Map<String, Object> address = (Map<String, Object>) spy.jpaAttributes.get("address");
assertEquals(1, address.size());
final Object[] keys = address.keySet().toArray();
assertEquals("country", keys[0].toString());
}
@SuppressWarnings("unchecked")
@Test
void testTwoComplexPropertiesOnePropertyProvided() throws ODataApplicationException {
// .../Organizations('4')/AdministrativeInformation/Updated/By
final RequestHandleSpy spy = prepareDeleteAdminInfo();
processor.clearFields(request, new ODataResponse());
assertEquals(1, spy.jpaAttributes.size());
final Map<String, Object> adminInfo = (Map<String, Object>) spy.jpaAttributes.get("administrativeInformation");
assertEquals(1, adminInfo.size());
final Map<String, Object> update = (Map<String, Object>) adminInfo.get("updated");
assertEquals(1, update.size());
final Object[] keys = update.keySet().toArray();
assertEquals("by", keys[0].toString());
}
@SuppressWarnings("unchecked")
@Test
void testTwoComplexPropertiesOnePropertyValueProvided() throws ODataApplicationException {
// .../Organizations('4')/AdministrativeInformation/Updated/By/$value
final RequestHandleSpy spy = prepareDeleteAdminInfo();
UriResourceValue uriProperty;
uriProperty = mock(UriResourceValue.class);
pathParts.add(uriProperty);
processor.clearFields(request, new ODataResponse());
assertEquals(1, spy.jpaAttributes.size());
final Map<String, Object> adminInfo = (Map<String, Object>) spy.jpaAttributes.get("administrativeInformation");
assertEquals(1, adminInfo.size());
final Map<String, Object> update = (Map<String, Object>) adminInfo.get("updated");
assertEquals(1, update.size());
final Object[] keys = update.keySet().toArray();
assertEquals("by", keys[0].toString());
}
@Test
void testBeginIsCalledOnNoTransaction() throws ODataApplicationException {
// .../Organizations('35')/Name2
prepareDeleteName2();
processor.clearFields(request, new ODataResponse());
verify(factory, times(1)).createTransaction();
}
@Test
void testBeginIsNotCalledOnTransaction() throws ODataApplicationException {
// .../Organizations('35')/Name2
prepareDeleteName2();
when(factory.hasActiveTransaction()).thenReturn(true);
processor.clearFields(request, new ODataResponse());
verify(factory, times(0)).createTransaction();
}
@Test
void testCommitIsCalledOnNoTransaction() throws ODataApplicationException {
// .../Organizations('35')/Name2
prepareDeleteName2();
processor.clearFields(request, new ODataResponse());
verify(transaction, times(1)).commit();
}
@Test
void testCommitIsNotCalledOnTransaction() throws ODataApplicationException {
// .../Organizations('35')/Name2
prepareDeleteName2();
when(factory.hasActiveTransaction()).thenReturn(true);
processor.clearFields(request, new ODataResponse());
verify(transaction, times(0)).commit();
}
@Test
void testErrorReturnCodeWithRollback() throws ODataJPATransactionException {
// .../Organizations('35')/Name2
final ODataResponse response = new ODataResponse();
final RequestHandleSpy spy = prepareDeleteName2();
spy.raiseException(1);
final ODataApplicationException act = assertThrows(ODataApplicationException.class,
() -> processor.clearFields(request, response));
assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), act.getStatusCode());
verify(transaction, times(1)).rollback();
}
@Test
void testErrorReturnCodeWithOutRollback() throws ODataJPATransactionException {
// .../Organizations('35')/Name2
final ODataResponse response = new ODataResponse();
final RequestHandleSpy spy = prepareDeleteName2();
spy.raiseException(1);
when(factory.hasActiveTransaction()).thenReturn(true);
final ODataApplicationException act = assertThrows(ODataApplicationException.class, () -> processor.clearFields(
request,
response));
assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), act.getStatusCode());
verify(transaction, times(0)).rollback();
}
@Test
void testReRaiseWithRollback() throws ODataJPATransactionException {
// .../Organizations('35')/Name2
final ODataResponse response = new ODataResponse();
final RequestHandleSpy spy = prepareDeleteName2();
spy.raiseException(2);
final ODataJPAProcessException act = assertThrows(ODataJPAProcessException.class,
() -> processor.clearFields(request, response));
assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), act.getStatusCode());
verify(transaction, times(1)).rollback();
}
@Test
void testReRaiseReturnCodeWithOutRollback() throws ODataJPAProcessException {
// .../Organizations('35')/Name2
final ODataResponse response = new ODataResponse();
final RequestHandleSpy spy = prepareDeleteName2();
spy.raiseException(2);
when(factory.hasActiveTransaction()).thenReturn(true);
final ODataJPAProcessorException act = assertThrows(ODataJPAProcessorException.class,
() -> processor.clearFields(request, response));
assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), act.getStatusCode());
verify(transaction, times(0)).rollback();
}
@Test
void testCallsValidateChangesOnSuccessfulProcessing() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest otherRequest = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.clearFields(otherRequest, response);
assertEquals(1, spy.noValidateCalls);
}
@Test
void testDoesNotCallsValidateChangesOnForeignTransaction() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest otherRequest = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(factory.hasActiveTransaction()).thenReturn(Boolean.TRUE);
processor.clearFields(otherRequest, response);
assertEquals(0, spy.noValidateCalls);
}
@Test
void testDoesNotCallsValidateChangesOnError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest otherRequest = prepareSimpleRequest();
when(otherRequest.getMethod()).thenReturn(HttpMethod.POST);
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).updateEntity(any(JPARequestEntity.class), any(EntityManager.class),
any(HttpMethod.class));
assertThrows(ODataApplicationException.class, () -> processor.clearFields(otherRequest, response));
verify(handler, never()).validateChanges(em);
}
@Test
void testDoesRollbackIfValidateRaisesError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest otherRequest = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em);
assertThrows(ODataApplicationException.class, () -> processor.clearFields(otherRequest, response));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
private RequestHandleSpy prepareDeleteName2() {
UriResourcePrimitiveProperty uriProperty;
EdmProperty property;
uriProperty = mock(UriResourcePrimitiveProperty.class);
property = mock(EdmProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("Name2");
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
return spy;
}
private RequestHandleSpy prepareDeleteComment() {
UriResourcePrimitiveProperty uriProperty;
EdmProperty property;
uriProperty = mock(UriResourcePrimitiveProperty.class);
property = mock(EdmProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("Comment");
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
return spy;
}
private RequestHandleSpy prepareDeleteAddress() {
UriResourceComplexProperty uriProperty;
EdmProperty property;
uriProperty = mock(UriResourceComplexProperty.class);
property = mock(EdmProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("Address");
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
return spy;
}
private RequestHandleSpy prepareDeleteAddressCountry() {
final RequestHandleSpy spy = prepareDeleteAddress();
UriResourcePrimitiveProperty uriProperty;
EdmProperty property;
uriProperty = mock(UriResourcePrimitiveProperty.class);
property = mock(EdmProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("Country");
return spy;
}
private RequestHandleSpy prepareDeleteAdminInfo() {
UriResourceComplexProperty uriProperty;
EdmProperty property;
uriProperty = mock(UriResourceComplexProperty.class);
property = mock(EdmProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("AdministrativeInformation");
uriProperty = mock(UriResourceComplexProperty.class);
property = mock(EdmProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("Updated");
UriResourcePrimitiveProperty uriPrimitiveProperty;
uriPrimitiveProperty = mock(UriResourcePrimitiveProperty.class);
property = mock(EdmProperty.class);
pathParts.add(uriPrimitiveProperty);
when(uriPrimitiveProperty.getProperty()).thenReturn(property);
when(property.getName()).thenReturn("By");
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
return spy;
}
class RequestHandleSpy extends JPAAbstractCUDRequestHandler {
public int noValidateCalls;
public Map<String, Object> keyPredicates;
public Map<String, Object> jpaAttributes;
public JPAEntityType et;
public boolean called;
public Map<String, List<String>> headers;
private int raiseEx;
public Optional<JPAODataClaimProvider> claims;
public List<String> groups;
@Override
public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em,
final HttpMethod verb) throws ODataJPAProcessException {
this.et = requestEntity.getEntityType();
this.keyPredicates = requestEntity.getKeys();
this.jpaAttributes = requestEntity.getData();
this.headers = requestEntity.getAllHeader();
this.claims = requestEntity.getClaims();
this.groups = requestEntity.getGroups();
called = true;
if (raiseEx == 1)
throw new NullPointerException();
if (raiseEx == 2)
throw new ODataJPAProcessorException(MessageKeys.NOT_SUPPORTED_DELETE, HttpStatusCode.NOT_IMPLEMENTED);
return null;
}
void raiseException(final int type) {
this.raiseEx = type;
}
@Override
public void validateChanges(final EntityManager em) throws ODataJPAProcessException {
noValidateCalls++;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAEmptyDebuggerTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAEmptyDebuggerTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
class JPAEmptyDebuggerTest {
JPAEmptyDebugger cut;
@BeforeEach
void setup() {
cut = new JPAEmptyDebugger();
}
@Test
void testMeasurementCreated() {
try (JPARuntimeMeasurement measurement = cut.newMeasurement(cut, "firstTest")) {
assertEquals(0L, measurement.getMemoryConsumption());
}
assertTrue(cut.getRuntimeInformation().isEmpty());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole;
import com.sap.olingo.jpa.processor.core.testmodel.CommunicationData;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
class TestCreateDeltaBasedResult extends TestJPAModifyProcessor {
private JPACUDRequestProcessor cut;
private List<JPAElement> pathElements;
private Person beforeImagePerson;
private Person currentImagePerson;
private JPAAssociationPath path;
@BeforeEach
@Override
public void setup() throws Exception {
super.setup();
cut = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, new JPAConversionHelper());
pathElements = new ArrayList<>(3);
path = mock(JPAAssociationPath.class);
beforeImagePerson = new Person();
beforeImagePerson.setID("1");
currentImagePerson = new Person();
currentImagePerson.setID("1");
when(em.contains(beforeImagePerson)).thenReturn(Boolean.FALSE);
}
@Test
void testShallReturnNullIfBeforeImageNotPresent() throws ODataJPAProcessorException {
final JPAElement pathItem = mock(JPAElement.class);
pathElements.add(pathItem);
when(pathItem.getInternalName()).thenReturn("roles");
final Object act = cut.getLinkedInstanceBasedResultByDelta(beforeImagePerson, path, Optional.empty());
assertNull(act);
}
@Test
void testThrowsExceptionIfBeforeIfManaged() {
when(em.contains(beforeImagePerson)).thenReturn(Boolean.TRUE);
assertThrows(ODataJPAProcessorException.class, () -> {
cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable(beforeImagePerson));
});
}
@Test
void testShallReturnNullIfTargetEmpty() throws ODataJPAProcessorException {
prepareRole();
final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable(
beforeImagePerson));
assertNull(act);
}
@Test
void testShallReturnNullIfNoDeltaFound() throws ODataJPAProcessorException {
prepareRole();
final BusinessPartnerRole beforeRole = new BusinessPartnerRole();
beforeRole.setBusinessPartner(beforeImagePerson);
beforeRole.setRoleCategory("A");
beforeImagePerson.getRoles().add(beforeRole);
final Object act = cut.getLinkedInstanceBasedResultByDelta(beforeImagePerson, path, Optional.ofNullable(
beforeImagePerson));
assertNull(act);
}
@Test
void testShallReturnsValueIfDeltaFoundBeforeEmpty() throws ODataJPAProcessorException {
prepareRole();
final BusinessPartnerRole exp = new BusinessPartnerRole();
exp.setBusinessPartner(currentImagePerson);
exp.setRoleCategory("A");
currentImagePerson.getRoles().add(exp);
final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable(
beforeImagePerson));
assertEquals(exp, act);
}
@Test
void testShallReturnsValueIfDeltaFoundBeforeOneNowTwo() throws ODataJPAProcessorException {
prepareRole();
final BusinessPartnerRole exp = new BusinessPartnerRole(currentImagePerson, "A");
currentImagePerson.getRoles().add(exp);
currentImagePerson.getRoles().add(new BusinessPartnerRole(currentImagePerson, "B"));
beforeImagePerson.getRoles().add(new BusinessPartnerRole(beforeImagePerson, "B"));
final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable(
beforeImagePerson));
assertEquals(exp, act);
}
@Test
void testShallReturnsValueIfDeltaFoundBeforeOneNowTwoInversOrder() throws ODataJPAProcessorException {
prepareRole();
currentImagePerson.getRoles().add(new BusinessPartnerRole(currentImagePerson, "B"));
beforeImagePerson.getRoles().add(new BusinessPartnerRole(beforeImagePerson, "B"));
final BusinessPartnerRole exp = new BusinessPartnerRole(currentImagePerson, "A");
currentImagePerson.getRoles().add(exp);
final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable(
beforeImagePerson));
assertEquals(exp, act);
}
@Test
void testShallReturnNewValueIfNotACollection() throws ODataJPAProcessorException {
final CommunicationData exp = prepareBeforeImageCommunicationData();
beforeImagePerson.setCommunicationData(exp);
final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable(
beforeImagePerson));
assertEquals(exp, act);
}
private void prepareRole() {
final JPAAssociationAttribute pathItem = mock(JPAAssociationAttribute.class);
pathElements.add(pathItem);
when(path.getPath()).thenReturn(pathElements);
when(pathItem.getInternalName()).thenReturn("roles");
when(path.getLeaf()).thenReturn(pathItem);
when(pathItem.isCollection()).thenReturn(Boolean.TRUE);
}
private CommunicationData prepareBeforeImageCommunicationData() {
final CommunicationData afterCommData = new CommunicationData();
currentImagePerson.setCommunicationData(afterCommData);
final JPAAssociationAttribute pathItem = mock(JPAAssociationAttribute.class);
pathElements.add(pathItem);
when(path.getPath()).thenReturn(pathElements);
when(pathItem.getInternalName()).thenReturn("communicationData");
when(path.getLeaf()).thenReturn(pathItem);
when(pathItem.isCollection()).thenReturn(Boolean.FALSE);
return afterCommData;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.uri.UriParameter;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
class TestJPADeleteProcessor extends TestJPAModifyProcessor {
@Test
void testSuccessReturnCode() throws ODataApplicationException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
when(requestContext.getCUDRequestHandler()).thenReturn(new RequestHandleSpy());
processor.deleteEntity(request, response);
assertEquals(204, response.getStatusCode());
}
@Test
void testThrowUnexpectedExceptionInCaseOfError() throws ODataJPAProcessException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
doThrow(NullPointerException.class).when(handler).deleteEntity(any(JPARequestEntity.class), any(
EntityManager.class));
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
final ODataApplicationException act = assertThrows(ODataApplicationException.class,
() -> processor.deleteEntity(request, response));
assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), act.getStatusCode());
}
@Test
void testThrowExpectedExceptionInCaseOfError() throws ODataJPAProcessException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).deleteEntity(any(JPARequestEntity.class), any(EntityManager.class));
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
final ODataApplicationException act = assertThrows(ODataApplicationException.class,
() -> processor.deleteEntity(request, response));
assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), act.getStatusCode());
}
@Test
void testConvertEntityType() throws ODataJPAProcessException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final RequestHandleSpy spy = new RequestHandleSpy();
final UriParameter param = mock(UriParameter.class);
keyPredicates.add(param);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(param.getName()).thenReturn("ID");
when(param.getText()).thenReturn("'1'");
processor.deleteEntity(request, response);
assertEquals("com.sap.olingo.jpa.processor.core.testmodel.Organization", spy.et.getInternalName());
}
@Test
void testHeadersProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final Map<String, List<String>> headers = new HashMap<>();
when(request.getAllHeaders()).thenReturn(headers);
headers.put("If-Match", Arrays.asList("2"));
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.deleteEntity(request, response);
assertNotNull(spy.headers);
assertEquals(1, spy.headers.size());
assertNotNull(spy.headers.get("If-Match"));
assertEquals("2", spy.headers.get("If-Match").get(0));
}
@Test
void testClaimsProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final RequestHandleSpy spy = new RequestHandleSpy();
final JPAODataClaimProvider provider = new JPAODataClaimsProvider();
final Optional<JPAODataClaimProvider> claims = Optional.of(provider);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(requestContext.getClaimsProvider()).thenReturn(claims);
processor.deleteEntity(request, response);
assertNotNull(spy.claims);
assertTrue(spy.claims.isPresent());
assertEquals(provider, spy.claims.get());
}
@Test
void testGroupsProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final RequestHandleSpy spy = new RequestHandleSpy();
final JPAODataGroupsProvider provider = new JPAODataGroupsProvider();
provider.addGroup("Person");
final Optional<JPAODataGroupProvider> groups = Optional.of(provider);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(requestContext.getGroupsProvider()).thenReturn(groups);
processor.deleteEntity(request, response);
assertNotNull(spy.groups);
assertFalse(spy.groups.isEmpty());
assertEquals("Person", spy.groups.get(0));
}
@Test
void testConvertKeySingleAttribute() throws ODataJPAProcessException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final RequestHandleSpy spy = new RequestHandleSpy();
final UriParameter param = mock(UriParameter.class);
keyPredicates.add(param);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(param.getName()).thenReturn("ID");
when(param.getText()).thenReturn("'1'");
processor.deleteEntity(request, response);
assertEquals(1, spy.keyPredicates.size());
assertTrue(spy.keyPredicates.get("iD") instanceof String);
assertEquals("1", spy.keyPredicates.get("iD"));
}
@Test
void testConvertKeyTwoAttributes() throws ODataJPAProcessException {
// BusinessPartnerRole
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final RequestHandleSpy spy = new RequestHandleSpy();
final UriParameter param1 = mock(UriParameter.class);
final UriParameter param2 = mock(UriParameter.class);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(ets.getName()).thenReturn("BusinessPartnerRoles");
when(param1.getName()).thenReturn("BusinessPartnerID");
when(param1.getText()).thenReturn("'1'");
when(param2.getName()).thenReturn("RoleCategory");
when(param2.getText()).thenReturn("'A'");
keyPredicates.add(param1);
keyPredicates.add(param2);
processor.deleteEntity(request, response);
assertEquals(2, spy.keyPredicates.size());
assertTrue(spy.keyPredicates.get("businessPartnerID") instanceof String);
assertEquals("1", spy.keyPredicates.get("businessPartnerID"));
assertTrue(spy.keyPredicates.get("roleCategory") instanceof String);
assertEquals("A", spy.keyPredicates.get("roleCategory"));
}
@Test
void testCallsValidateChangesOnSuccessfulProcessing() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.deleteEntity(request, response);
assertEquals(1, spy.noValidateCalls);
}
@Test
void testDoesNotCallsValidateChangesOnForeignTransaction() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(factory.hasActiveTransaction()).thenReturn(Boolean.TRUE);
when(requestContext.getEntityManager()).thenReturn(em);
processor = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, new JPAConversionHelper());
processor.deleteEntity(request, response);
assertEquals(0, spy.noValidateCalls);
}
@Test
void testDoesNotCallsValidateChangesOnError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).deleteEntity(any(JPARequestEntity.class), any(EntityManager.class));
assertThrows(ODataJPAProcessorException.class, () -> processor.deleteEntity(request, response));
verify(handler, never()).validateChanges(em);
}
@Test
void testDoesRollbackIfValidateRaisesError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(transaction.isActive()).thenReturn(Boolean.FALSE);
when(requestContext.getEntityManager()).thenReturn(em);
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
processor = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, new JPAConversionHelper());
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em);
assertThrows(ODataApplicationException.class, () -> processor.deleteEntity(request, response));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testBeginIsCalledOnNoTransaction() throws ODataApplicationException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = mock(ODataRequest.class);
when(requestContext.getCUDRequestHandler()).thenReturn(new RequestHandleSpy());
processor.deleteEntity(request, response);
verify(factory, times(1)).createTransaction();
}
class RequestHandleSpy extends JPAAbstractCUDRequestHandler {
public int noValidateCalls;
public Map<String, Object> keyPredicates;
public JPAEntityType et;
public Map<String, List<String>> headers;
public Optional<JPAODataClaimProvider> claims;
public List<String> groups;
@Override
public void deleteEntity(final JPARequestEntity entity, final EntityManager em) {
this.keyPredicates = entity.getKeys();
this.et = entity.getEntityType();
this.headers = entity.getAllHeader();
this.claims = entity.getClaims();
this.groups = entity.getGroups();
}
@Override
public void validateChanges(final EntityManager em) throws ODataJPAProcessException {
noValidateCalls++;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPANavigationRequestProcessorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPANavigationRequestProcessorTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.converter.JPAExpandResult.ROOT_RESULT_KEY;
import static com.sap.olingo.jpa.processor.core.processor.JPAETagValidationResult.NOT_MODIFIED;
import static com.sap.olingo.jpa.processor.core.processor.JPAETagValidationResult.PRECONDITION_FAILED;
import static com.sap.olingo.jpa.processor.core.processor.JPAETagValidationResult.SUCCESS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.query.JPAConvertibleResult;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class JPANavigationRequestProcessorTest extends TestBase {
private JPANavigationRequestProcessor cut;
private JPAODataRequestContextAccess requestContext;
private ServiceMetadata metadata;
private JPAExpandResult result;
private JPAHttpHeaderMap headers;
private UriInfoResource uriInfo;
private UriResource uriResource;
private OData odata;
@BeforeEach
void setup() throws ODataException {
getHelper();
requestContext = mock(JPAODataRequestContextAccess.class);
metadata = mock(ServiceMetadata.class);
uriInfo = mock(UriInfoResource.class);
uriResource = mock(UriResource.class);
result = mock(JPAExpandResult.class, withSettings().extraInterfaces(JPAConvertibleResult.class));
headers = mock(JPAHttpHeaderMap.class);
odata = OData.newInstance();
when(requestContext.getEdmProvider()).thenReturn(helper.edmProvider);
when(requestContext.getEntityManager()).thenReturn(emf.createEntityManager());
when(requestContext.getUriInfo()).thenReturn(uriInfo);
when(requestContext.getEtagHelper()).thenReturn(new JPAODataEtagHelperImpl(odata));
when(uriInfo.getUriResourceParts()).thenReturn(Collections.singletonList(uriResource));
cut = new JPANavigationRequestProcessor(OData.newInstance(), metadata, requestContext);
doReturn(helper.getJPAEntityType(Organization.class)).when(result).getEntityType();
}
@Test
void testNoEtagPropertySuccess() throws ODataJPAProcessorException, ODataJPAModelException {
final Tuple tuple = mock(Tuple.class);
final List<Tuple> rootResult = Collections.singletonList(tuple);
when(result.getResult(ROOT_RESULT_KEY)).thenReturn(rootResult);
when(headers.get(HttpHeader.IF_MATCH)).thenReturn(Arrays.asList("\"1\""));
doReturn(helper.getJPAEntityType(AdministrativeDivision.class)).when(result).getEntityType();
assertEquals(JPAETagValidationResult.SUCCESS, cut.validateEntityTag((JPAConvertibleResult) result, headers));
}
@Test
void testValidWithoutHeader() throws ODataJPAProcessorException {
assertEquals(JPAETagValidationResult.SUCCESS, cut.validateEntityTag((JPAConvertibleResult) result, headers));
}
@Test
void testValidIfMatchWithoutResult() throws ODataJPAProcessorException {
when(result.getResult(ROOT_RESULT_KEY)).thenReturn(Collections.emptyList());
when(headers.get(HttpHeader.IF_MATCH.toLowerCase(Locale.ENGLISH))).thenReturn(Arrays.asList("\"1\""));
assertEquals(JPAETagValidationResult.SUCCESS, cut.validateEntityTag((JPAConvertibleResult) result, headers));
}
@Test
void testValidIfNoneMatchWithoutResult() throws ODataJPAProcessorException {
when(result.getResult(ROOT_RESULT_KEY)).thenReturn(Collections.emptyList());
when(headers.get(HttpHeader.IF_NONE_MATCH.toLowerCase(Locale.ENGLISH))).thenReturn(Arrays.asList("\"0\""));
assertEquals(JPAETagValidationResult.SUCCESS, cut.validateEntityTag((JPAConvertibleResult) result, headers));
}
private static Stream<Arguments> provideIfMatchHeader() {
return Stream.of(
Arguments.of(Arrays.asList("\"0\""), PRECONDITION_FAILED, "Not matching eTag: 412 ecxpected"),
Arguments.of(Arrays.asList("\"0\"", "\"3\""), PRECONDITION_FAILED, "None matching eTag: 412 ecxpected"),
Arguments.of(Arrays.asList("\"1\""), SUCCESS, "Matching eTag: 200 ecxpected"),
Arguments.of(Arrays.asList("\"2\"", "\"1\""), SUCCESS, "One Matching eTag: 200 ecxpected"),
Arguments.of(Arrays.asList("*"), SUCCESS, "* eTag: 200 ecxpected"));
}
@ParameterizedTest
@MethodSource("provideIfMatchHeader")
void testIfMatchHeader(final List<String> etag, final JPAETagValidationResult exp, final String message)
throws ODataException {
final Tuple tuple = mock(Tuple.class);
final List<Tuple> rootResult = Collections.singletonList(tuple);
when(result.getResult(ROOT_RESULT_KEY)).thenReturn(rootResult);
when(headers.get(HttpHeader.IF_MATCH)).thenReturn(etag);
when(tuple.get("ETag")).thenReturn(Integer.valueOf(1));
assertEquals(exp, cut.validateEntityTag((JPAConvertibleResult) result, headers), message);
}
private static Stream<Arguments> provideIfNoneMatchHeader() {
return Stream.of(
Arguments.of(Arrays.asList("\"1\""), NOT_MODIFIED, "Matching eTag: 304 ecxpected"),
Arguments.of(Arrays.asList("\"2\"", "\"1\""), NOT_MODIFIED, "One Matching eTag: 304 ecxpected"),
Arguments.of(Arrays.asList("\"0\""), SUCCESS, "Not matching eTag: 200 ecxpected"),
Arguments.of(Arrays.asList("\"0\"", "\"3\""), SUCCESS, "None matching eTag: 200 ecxpected"),
Arguments.of(Arrays.asList("*"), NOT_MODIFIED, "* matches any eTag: 304 ecxpected"));
}
@ParameterizedTest
@MethodSource("provideIfNoneMatchHeader")
void testIfNoneMatchHeader(final List<String> etag, final JPAETagValidationResult exp, final String message)
throws ODataException {
final Tuple tuple = mock(Tuple.class);
final List<Tuple> rootResult = Collections.singletonList(tuple);
when(result.getResult(ROOT_RESULT_KEY)).thenReturn(rootResult);
when(headers.get(HttpHeader.IF_NONE_MATCH)).thenReturn(etag);
when(tuple.get("ETag")).thenReturn(Integer.valueOf(1));
assertEquals(exp, cut.validateEntityTag((JPAConvertibleResult) result, headers), message);
}
private static Stream<Arguments> provideHeaderException() {
return Stream.of(
Arguments.of(Arrays.asList("\"1\""), HttpHeader.IF_MATCH),
Arguments.of(Arrays.asList("\"0\""), HttpHeader.IF_NONE_MATCH));
}
@ParameterizedTest
@MethodSource("provideHeaderException")
void testThrowExceptionMultipleResults(final List<String> etag, final String header) {
final Tuple tuple1 = mock(Tuple.class);
final Tuple tuple2 = mock(Tuple.class);
final List<Tuple> rootResult = Arrays.asList(tuple1, tuple2);
when(result.getResult(ROOT_RESULT_KEY)).thenReturn(rootResult);
when(headers.get(header)).thenReturn(etag);
assertThrows(ODataJPAProcessorException.class,
() -> cut.validateEntityTag((JPAConvertibleResult) result, headers));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAActionRequestProcessorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAActionRequestProcessorTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
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.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.apache.olingo.commons.api.data.Annotatable;
import org.apache.olingo.commons.api.data.Parameter;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.commons.api.edm.EdmAction;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.EdmReturnType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.edm.provider.CsdlReturnType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.deserializer.DeserializerResult;
import org.apache.olingo.server.api.deserializer.ODataDeserializer;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriHelper;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceAction;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataEtagHelper;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.CommunicationData;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.testobjects.FileAccess;
import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionActionConstructor;
import com.sap.olingo.jpa.processor.core.testobjects.TestJavaActionNoParameter;
import com.sap.olingo.jpa.processor.core.testobjects.TestJavaActions;
class JPAActionRequestProcessorTest {
private JPAActionRequestProcessor cut;
private ContentType requestFormat;
@Mock
private ODataRequest request;
@Mock
private ODataResponse response;
@Mock
private OData odata;
@Mock
private ODataDeserializer deserializer;
@Mock
private JPAOperationSerializer serializer;
@Mock
private JPAODataRequestContextAccess requestContext;
@Mock
private JPAServiceDocument sd;
@Mock
private UriInfo uriInfo;
private List<UriResource> uriResources;
@Mock
private UriResourceAction resource;
@Mock
private EdmAction edmAction;
@Mock
private JPAAction action;
private Map<String, Parameter> actionParameter;
@Mock
private CsdlReturnType returnType;
@Mock
private UriResourceEntitySet bindingEntity;
@Mock
private UriHelper uriHelper;
@Mock
private JPAODataEtagHelper etagHelper;
@BeforeEach
void setup() throws ODataException {
MockitoAnnotations.openMocks(this);
uriResources = new ArrayList<>();
uriResources.add(resource);
actionParameter = new HashMap<>();
final EntityManager em = mock(EntityManager.class);
final CriteriaBuilder cb = mock(CriteriaBuilder.class);
final JPAEdmProvider edmProvider = mock(JPAEdmProvider.class);
final DeserializerResult dResult = mock(DeserializerResult.class);
final SerializerResult serializerResult = mock(SerializerResult.class);
when(requestContext.getEntityManager()).thenReturn(em);
when(em.getCriteriaBuilder()).thenReturn(cb);
when(requestContext.getEdmProvider()).thenReturn(edmProvider);
when(edmProvider.getServiceDocument()).thenReturn(sd);
when(requestContext.getUriInfo()).thenReturn(uriInfo);
when(requestContext.getSerializer()).thenReturn(serializer);
when(requestContext.getRequestParameter()).thenReturn(new JPARequestParameterHashMap());
when(requestContext.getHeader()).thenReturn(new JPAHttpHeaderHashMap());
when(requestContext.getEtagHelper()).thenReturn(etagHelper);
when(serializer.serialize(any(Annotatable.class), any(EdmType.class), any(ODataRequest.class)))
.thenReturn(serializerResult);
when(serializer.getContentType()).thenReturn(ContentType.APPLICATION_JSON);
when(uriInfo.getUriResourceParts()).thenReturn(uriResources);
when(resource.getAction()).thenReturn(edmAction);
when(edmAction.isBound()).thenReturn(Boolean.FALSE);
when(sd.getAction(edmAction)).thenReturn(action);
when(odata.createDeserializer((ContentType) any())).thenReturn(deserializer);
when(odata.createUriHelper()).thenReturn(uriHelper);
when(deserializer.actionParameters(request.getBody(), resource.getAction())).thenReturn(dResult);
when(dResult.getActionParameters()).thenReturn(actionParameter);
requestFormat = ContentType.APPLICATION_JSON;
cut = new JPAActionRequestProcessor(odata, requestContext);
}
@Test
void testCallsConstructorWithoutParameter() throws NoSuchMethodException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
setConstructorAndMethod("unboundReturnPrimitiveNoParameter");
cut.performAction(request, response, requestFormat);
assertEquals(1, TestJavaActionNoParameter.constructorCalls);
}
@SuppressWarnings("unchecked")
@Test
void testCallsConstructorWithParameter() throws NoSuchMethodException, SecurityException, ODataApplicationException {
TestJavaActions.constructorCalls = 0;
@SuppressWarnings("rawtypes")
final Constructor constructor = TestJavaActions.class.getConstructors()[0];
final Method method = TestJavaActions.class.getMethod("unboundWithOutParameter");
when(action.getConstructor()).thenReturn(constructor);
when(action.getMethod()).thenReturn(method);
when(action.getReturnType()).thenReturn(null);
cut.performAction(request, response, requestFormat);
assertEquals(1, TestJavaActions.constructorCalls);
}
@SuppressWarnings("unchecked")
@Test
void testCallsActionVoidNoParameterReturnNoContent() throws NoSuchMethodException, SecurityException,
ODataApplicationException {
@SuppressWarnings("rawtypes")
final Constructor constructor = TestJavaActions.class.getConstructors()[0];
final Method method = TestJavaActions.class.getMethod("unboundWithOutParameter");
when(action.getConstructor()).thenReturn(constructor);
when(action.getMethod()).thenReturn(method);
when(action.getReturnType()).thenReturn(null);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
}
@SuppressWarnings("unchecked")
@Test
void testCallsActionPrimitiveNoParameterReturnValue() throws NoSuchMethodException, SecurityException,
SerializerException, ODataApplicationException {
@SuppressWarnings("rawtypes")
final Constructor constructor = TestJavaActions.class.getConstructors()[0];
final Method method = TestJavaActions.class.getMethod("unboundReturnFacetNoParameter");
when(action.getConstructor()).thenReturn(constructor);
when(action.getMethod()).thenReturn(method);
final JPAOperationResultParameter rParam = mock(JPAOperationResultParameter.class);
when(action.getResultParameter()).thenReturn(rParam);
final EdmReturnType rt = mock(EdmReturnType.class);
final EdmType type = mock(EdmType.class);
when(edmAction.getReturnType()).thenReturn(rt);
when(rt.getType()).thenReturn(type);
when(type.getKind()).thenReturn(EdmTypeKind.PRIMITIVE);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(200);
verify(serializer, times(1)).serialize(any(Annotatable.class), eq(type), any(ODataRequest.class));
}
@SuppressWarnings("unchecked")
@Test
void testCallsActionEntityNoParameterReturnValue() throws NoSuchMethodException,
SecurityException, SerializerException, ODataApplicationException {
@SuppressWarnings("rawtypes")
final Constructor constructor = TestJavaActions.class.getConstructors()[0];
final Method method = TestJavaActions.class.getMethod("returnEmbeddable");
when(action.getConstructor()).thenReturn(constructor);
when(action.getMethod()).thenReturn(method);
final JPAOperationResultParameter rParam = mock(JPAOperationResultParameter.class);
when(action.getResultParameter()).thenReturn(rParam);
final EdmReturnType rt = mock(EdmReturnType.class);
final EdmComplexType type = mock(EdmComplexType.class);
when(edmAction.getReturnType()).thenReturn(rt);
when(rt.getType()).thenReturn(type);
when(type.getKind()).thenReturn(EdmTypeKind.COMPLEX);
final JPAStructuredType st = mock(JPAStructuredType.class);
when(sd.getComplexType((EdmComplexType) any())).thenReturn(st);
doReturn(CommunicationData.class).when(st).getTypeClass();
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(200);
verify(serializer, times(1)).serialize(any(Annotatable.class), eq(type), any(ODataRequest.class));
}
@Test
void testCallsActionVoidOneParameterReturnNoContent() throws NoSuchMethodException, SecurityException,
ODataJPAModelException, NumberFormatException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
final Method method = setConstructorAndMethod("unboundVoidOneParameter", Short.class);
addParameter(method, Short.valueOf("10"), "A", 0);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
assertEquals((short) 10, TestJavaActionNoParameter.param1);
}
@Test
void testCallsActionVoidOneEnumerationParameterReturnNoContent() throws NoSuchMethodException, SecurityException,
ODataJPAModelException, NumberFormatException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
final Method method = setConstructorAndMethod("unboundVoidOneEnumerationParameter", FileAccess.class);
addParameter(method, FileAccess.Create, "AccessRights", 0);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
assertEquals(FileAccess.Create, TestJavaActionNoParameter.enumeration);
}
@Test
void testCallsActionVoidTwoParameterReturnNoContent() throws NoSuchMethodException, SecurityException,
ODataJPAModelException, NumberFormatException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
final Method method = setConstructorAndMethod("unboundVoidTwoParameter", Short.class, Integer.class);
addParameter(method, Short.valueOf("10"), "A", 0);
addParameter(method, Integer.valueOf("200000"), "B", 1);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
assertEquals((short) 10, TestJavaActionNoParameter.param1);
}
@Test
void testCallsActionVoidOneParameterNullableGivenNullReturnNoContent() throws NoSuchMethodException,
SecurityException, ODataJPAModelException, NumberFormatException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
final Method method = setConstructorAndMethod("unboundVoidOneParameter", Short.class);
addParameter(method, null, "A", 0);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
assertNull(TestJavaActionNoParameter.param1);
}
@Test
void testCallsActionVoidOnlyBindingParameter() throws NoSuchMethodException, SecurityException,
ODataJPAModelException, NumberFormatException, EdmPrimitiveTypeException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
final Method method = setConstructorAndMethod("boundOnlyBinding", AdministrativeDivision.class);
when(edmAction.isBound()).thenReturn(Boolean.TRUE);
uriResources.add(0, bindingEntity);
setBindingParameter(method);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
assertNotNull(TestJavaActionNoParameter.bindingParam);
assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID());
}
@Test
void testCallsActionVoidBindingParameterPlusTwoBothNull() throws NoSuchMethodException, SecurityException,
ODataJPAModelException, NumberFormatException, EdmPrimitiveTypeException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
final Method method = setConstructorAndMethod("boundBindingPlus", AdministrativeDivision.class, Short.class,
Integer.class);
when(edmAction.isBound()).thenReturn(Boolean.TRUE);
uriResources.add(0, bindingEntity);
setBindingParameter(method);
JPAParameter jpaParam = mock(JPAParameter.class);
when(action.getParameter(method.getParameters()[1])).thenReturn(jpaParam);
when(jpaParam.getName()).thenReturn("A");
jpaParam = mock(JPAParameter.class);
when(action.getParameter(method.getParameters()[2])).thenReturn(jpaParam);
when(jpaParam.getName()).thenReturn("B");
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
assertNotNull(TestJavaActionNoParameter.bindingParam);
assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID());
assertNull(TestJavaActionNoParameter.param1);
assertNull(TestJavaActionNoParameter.param2);
}
@Test
void testCallsActionVoidBindingParameterPlusTwoFirstNull() throws NoSuchMethodException, SecurityException,
ODataJPAModelException, NumberFormatException, EdmPrimitiveTypeException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
final Method method = setConstructorAndMethod("boundBindingPlus", AdministrativeDivision.class, Short.class,
Integer.class);
when(edmAction.isBound()).thenReturn(Boolean.TRUE);
uriResources.add(0, bindingEntity);
setBindingParameter(method);
final JPAParameter jpaParam = mock(JPAParameter.class);
when(action.getParameter(method.getParameters()[1])).thenReturn(jpaParam);
when(jpaParam.getName()).thenReturn("A");
addParameter(method, 20, "B", 2);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
assertNotNull(TestJavaActionNoParameter.bindingParam);
assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID());
assertNull(TestJavaActionNoParameter.param1);
assertEquals(20, TestJavaActionNoParameter.param2);
}
@Test
void testCallsActionVoidBindingParameterAbstractCallBySubtype() throws NoSuchMethodException, SecurityException,
ODataJPAModelException, NumberFormatException, ODataApplicationException {
TestJavaActionNoParameter.resetCalls();
final Method method = setConstructorAndMethod("boundBindingSuperType", BusinessPartner.class);
when(edmAction.isBound()).thenReturn(Boolean.TRUE);
uriResources.add(0, bindingEntity);
final JPAParameter bindingParam = addParameter(method, null, "Root", 0);
doReturn(BusinessPartner.class).when(bindingParam).getType();
final JPAEntityType et = mock(JPAEntityType.class);
when(sd.getEntity((EdmType) any())).thenReturn(et);
doReturn(Organization.class).when(et).getTypeClass();
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
}
@Test
void testCallsWithConstructorParameterValue() throws NoSuchMethodException, ODataJPAModelException,
ODataApplicationException {
final Method method = setConstructorAndMethod(TestFunctionActionConstructor.class, "action", LocalDate.class);
addParameter(method, LocalDate.now(), "date", 0);
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(204);
}
@Test
void testEtagHeaderFilledForEntity() throws NoSuchMethodException, ODataApplicationException, ODataJPAModelException,
SerializerException {
setConstructorAndMethod(TestJavaActions.class, "returnsEntityWithETag");
final EdmReturnType edmReturnType = mock(EdmReturnType.class);
final EdmEntityType type = mock(EdmEntityType.class);
when(edmAction.getReturnType()).thenReturn(edmReturnType);
when(edmReturnType.getType()).thenReturn(type);
when(type.getKind()).thenReturn(EdmTypeKind.ENTITY);
final JPAOperationResultParameter resultParameter = mock(JPAOperationResultParameter.class);
when(action.getResultParameter()).thenReturn(resultParameter);
when(resultParameter.isCollection()).thenReturn(false);
final JPAEntityType jpaType = mock(JPAEntityType.class);
final JPAAttribute idAttribute = createJPAAttribute("iD", "Test", "ID");
final JPAAttribute etagAttribute = createJPAAttribute("eTag", "Test", "ETag");
final List<JPAAttribute> attributes = Arrays.asList(idAttribute, etagAttribute);
final JPAPath etagPath = mock(JPAPath.class);
final JPAElement pathPart = mock(JPAElement.class);
when(sd.getEntity(type)).thenReturn(jpaType);
when(jpaType.getExternalFQN()).thenReturn(new FullQualifiedName("Test", "Person"));
doReturn(Person.class).when(jpaType).getTypeClass();
when(jpaType.getAttributes()).thenReturn(attributes);
when(jpaType.hasEtag()).thenReturn(true);
when(jpaType.getEtagPath()).thenReturn(etagPath);
when(etagPath.getPath()).thenReturn(Arrays.asList(pathPart));
when(pathPart.getInternalName()).thenReturn("eTag");
when(etagHelper.asEtag(any(), any())).thenReturn("\"7\"");
when(uriHelper.buildKeyPredicate(any(), any())).thenReturn("example.org");
cut.performAction(request, response, requestFormat);
verify(response, times(1)).setStatusCode(200);
verify(response, times(1)).setHeader(HttpHeader.ETAG, "\"7\"");
}
private JPAAttribute createJPAAttribute(final String internalName, final String namespace,
final String externalName) {
final JPAAttribute attribute = mock(JPAAttribute.class);
when(attribute.getInternalName()).thenReturn(internalName);
when(attribute.getExternalName()).thenReturn(externalName);
when(attribute.getExternalFQN()).thenReturn(new FullQualifiedName(namespace, externalName));
return attribute;
}
private void setBindingParameter(final Method method) throws ODataJPAModelException, EdmPrimitiveTypeException {
final JPAParameter bindingParam = addParameter(method, null, "Root", 0);
doReturn(AdministrativeDivision.class).when(bindingParam).getType();
final List<UriParameter> keys = new ArrayList<>();
final UriParameter key1 = mock(UriParameter.class);
when(bindingEntity.getKeyPredicates()).thenReturn(keys);
when(key1.getName()).thenReturn("CodeID");
when(key1.getText()).thenReturn("LAU2");
keys.add(key1);
final JPAEntityType et = mock(JPAEntityType.class);
final JPAPath codePath = mock(JPAPath.class);
final JPAAttribute code = mock(JPAAttribute.class);
final EdmPrimitiveType edmString = mock(EdmPrimitiveType.class);
final CsdlProperty edmProperty = mock(CsdlProperty.class);
when(sd.getEntity((EdmType) any())).thenReturn(et);
when(et.getPath("CodeID")).thenReturn(codePath);
when(et.getAttribute("codeID")).thenReturn(Optional.of(code));
doReturn(AdministrativeDivision.class).when(et).getTypeClass();
when(codePath.getLeaf()).thenReturn(code);
when(code.getInternalName()).thenReturn("codeID");
doReturn(String.class).when(code).getType();
when(code.getProperty()).thenReturn(edmProperty);
when(code.getEdmType()).thenReturn(EdmPrimitiveTypeKind.String);
when(odata.createPrimitiveTypeInstance(EdmPrimitiveTypeKind.String)).thenReturn(edmString);
when(edmString.fromUriLiteral("LAU2")).thenReturn("LAU2");
when(edmString.valueOfString("LAU2", false, 0, 0, 0, true, code.getType())).thenAnswer(
new Answer<String>() {
@Override
public String answer(final InvocationOnMock invocation) throws Throwable {
return "LAU2";
}
});
}
private JPAParameter addParameter(final Method method, final Object value, final String name, final int index)
throws ODataJPAModelException {
final Parameter param = mock(Parameter.class);
when(param.getValue()).thenReturn(value);
when(param.getName()).thenReturn(name);
when(param.getValueType()).thenReturn(ValueType.PRIMITIVE);
actionParameter.put(name, param);
final JPAParameter jpaParam = mock(JPAParameter.class);
when(action.getParameter(method.getParameters()[index])).thenReturn(jpaParam);
when(jpaParam.getName()).thenReturn(name);
return jpaParam;
}
@SuppressWarnings("unchecked")
private Method setConstructorAndMethod(final String methodName, final Class<?>... parameterTypes)
throws NoSuchMethodException {
@SuppressWarnings("rawtypes")
final Constructor constructor = TestJavaActionNoParameter.class.getConstructors()[0];
final Method method = TestJavaActionNoParameter.class.getMethod(methodName, parameterTypes);
when(action.getConstructor()).thenReturn(constructor);
when(action.getMethod()).thenReturn(method);
when(action.getReturnType()).thenReturn(null);
return method;
}
@SuppressWarnings("unchecked")
private Method setConstructorAndMethod(final Class<?> clazz, final String methodName,
final Class<?>... parameterTypes) throws NoSuchMethodException {
@SuppressWarnings("rawtypes")
final Constructor constructor = clazz.getConstructors()[0];
final Method method = clazz.getMethod(methodName, parameterTypes);
when(action.getConstructor()).thenReturn(constructor);
when(action.getMethod()).thenReturn(method);
when(action.getReturnType()).thenReturn(null);
return method;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataRequestContextBuilderTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataRequestContextBuilderTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import jakarta.persistence.EntityManager;
import org.apache.olingo.server.api.debug.DefaultDebugSupport;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataDefaultTransactionFactory;
import com.sap.olingo.jpa.processor.core.api.JPAODataExternalRequestContext.Builder;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory;
class JPAODataRequestContextBuilderTest {
private static final String PARAMETER_VALUE = "Test";
private static final String PARAMETER_NAME = "MyParameter";
private Builder cut;
@BeforeEach
void setup() {
cut = JPAODataRequestContext.with();
}
@Test
void testCreateWithSetDebugSupport() {
final DefaultDebugSupport exp = new DefaultDebugSupport();
cut.setDebugSupport(exp);
assertEquals(exp, cut.build().getDebuggerSupport());
}
@Test
void testCreateWithSetClaimsProvider() {
final JPAODataClaimProvider exp = new JPAODataClaimsProvider();
cut.setClaimsProvider(exp);
final JPAODataRequestContext act = cut.build();
assertTrue(act.getClaimsProvider().isPresent());
assertEquals(exp, act.getClaimsProvider().get());
}
@Test
void testCreateWithSetGroupsProvider() {
final JPAODataGroupProvider exp = new JPAODataGroupsProvider();
cut.setGroupsProvider(exp);
final JPAODataRequestContext act = cut.build();
assertTrue(act.getGroupsProvider().isPresent());
assertEquals(exp, act.getGroupsProvider().get());
}
@Test
void testCreateWithSetTransactionFactory() {
final EntityManager em = mock(EntityManager.class);
final JPAODataTransactionFactory exp = new JPAODataDefaultTransactionFactory(em);
cut.setTransactionFactory(exp);
final JPAODataRequestContext act = cut.build();
assertEquals(exp, act.getTransactionFactory());
}
@Test
void testCreateWithSetEntityManager() {
final EntityManager exp = mock(EntityManager.class);
cut.setEntityManager(exp);
final JPAODataRequestContext act = cut.build();
assertEquals(exp, act.getEntityManager());
}
@Test
void testThrowsExceptionOnEntityManagerIsNull() {
assertThrows(NullPointerException.class, () -> cut.setEntityManager(null));
}
@Test
void testCreateWithSetCUDRequestHandler() {
final JPACUDRequestHandler exp = mock(JPACUDRequestHandler.class);
cut.setCUDRequestHandler(exp);
final JPAODataRequestContext act = cut.build();
assertEquals(exp, act.getCUDRequestHandler());
}
@Test
void testCreateWithSetCustomParameter() {
cut.setParameter(PARAMETER_NAME, PARAMETER_VALUE);
final JPAODataRequestContext act = cut.build();
assertEquals(PARAMETER_VALUE, act.getRequestParameter().get(PARAMETER_NAME));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
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.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmEntityContainer;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.commons.core.edm.primitivetype.EdmString;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializerFactory;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole;
import com.sap.olingo.jpa.processor.core.testmodel.FullNameCalculator;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
class TestJPACreateProcessor extends TestJPAModifyProcessor {
@Test
void testHookIsCalled() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertTrue(spy.called);
}
@Test
void testEntityTypeProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals("Organization", spy.et.getExternalName());
}
@SuppressWarnings("unchecked")
@Test
void testAttributesProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final Map<String, Object> attributes = new HashMap<>(1);
attributes.put("ID", "35");
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(convHelper.convertProperties(ArgumentMatchers.any(OData.class), ArgumentMatchers.any(JPAStructuredType.class),
ArgumentMatchers.any(
List.class))).thenReturn(attributes);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.jpaAttributes);
assertEquals(1, spy.jpaAttributes.size());
assertEquals("35", spy.jpaAttributes.get("ID"));
}
@Test
void testHeadersProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final Map<String, List<String>> headers = new HashMap<>();
when(request.getAllHeaders()).thenReturn(headers);
headers.put("If-Match", Arrays.asList("2"));
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.headers);
assertEquals(1, spy.headers.size());
assertNotNull(spy.headers.get("If-Match"));
assertEquals("2", spy.headers.get("If-Match").get(0));
}
@Test
void testClaimsProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
final JPAODataClaimProvider provider = new JPAODataClaimsProvider();
final Optional<JPAODataClaimProvider> claims = Optional.of(provider);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(requestContext.getClaimsProvider()).thenReturn(claims);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.claims);
assertTrue(spy.claims.isPresent());
assertEquals(provider, spy.claims.get());
}
@Test
void testGroupsProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
final JPAODataGroupsProvider provider = new JPAODataGroupsProvider();
provider.addGroup("Person");
final Optional<JPAODataGroupProvider> groups = Optional.of(provider);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(requestContext.getGroupsProvider()).thenReturn(groups);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.groups);
assertFalse(spy.groups.isEmpty());
assertEquals("Person", spy.groups.get(0));
}
@Test
void testThrowExpectedExceptionInCaseOfError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).createEntity(any(JPARequestEntity.class), any(EntityManager.class));
try {
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
} catch (final ODataApplicationException e) {
assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode());
return;
}
fail();
}
@Test
void testThrowUnexpectedExceptionInCaseOfError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(NullPointerException.class).when(handler).createEntity(any(JPARequestEntity.class), any(
EntityManager.class));
try {
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
} catch (final ODataApplicationException e) {
assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode());
return;
}
fail();
}
@Test
void testMinimalResponseLocationHeader() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION));
}
@Test
void testMinimalResponseODataEntityIdHeader() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.ODATA_ENTITY_ID));
}
@Test
void testMinimalResponseStatusCode() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode());
}
@Test
void testMinimalResponsePreferApplied() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals("return=minimal", response.getHeader(HttpHeader.PREFERENCE_APPLIED));
}
@Test
void testRepresentationResponseStatusCode() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy());
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode());
}
@Test
void testRepresentationResponseStatusCodeMapResult() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy());
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode());
}
@Test
void testRepresentationResponseContent() throws ODataException, IOException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy());
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
final byte[] act = new byte[100];
response.getContent().read(act);
final String s = new String(act).trim();
assertEquals("{\"ID\":\"35\"}", s);
}
@Test
void testPersonResponseContent() throws ODataException, IOException {
final JPAODataSessionContextAccess context = mock(JPAODataSessionContextAccess.class);
final EdmType propertyType = mock(EdmPrimitiveType.class);
final EdmProperty propertyFN = createProperty("FullName", EdmString.getInstance());
final EdmProperty propertyID = createProperty("ID", EdmString.getInstance());
final EdmEntityType entityType = mock(EdmEntityType.class);
final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.Person");
when(ets.getEntityType()).thenReturn(entityType);
when(entityType.getFullQualifiedName()).thenReturn(fqn);
when(entityType.getPropertyNames()).thenReturn(Arrays.asList("FullName", "ID"));
when(entityType.getStructuralProperty("FullName")).thenReturn(propertyFN);
when(entityType.getStructuralProperty("ID")).thenReturn(propertyID);
when(propertyType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE);
final JPASerializer jpaSerializer = new JPASerializerFactory(odata, serviceMetadata, context)
.createCUDSerializer(ContentType.APPLICATION_JSON, uriInfo, Optional.empty());
when(requestContext.getSerializer()).thenReturn(jpaSerializer);
when(requestContext.getCalculator(any())).thenReturn(Optional.of(new FullNameCalculator()));
when(ets.getName()).thenReturn("Persons");
processor = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, convHelper);
final Person person = new Person();
person.setID("35");
person.setFirstName("Willi");
person.setLastName("Wunder");
final ODataResponse response = new ODataResponse();
final ODataRequest request = preparePersonRequest(new RequestHandleSpy(person));
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
final byte[] act = new byte[1000];
response.getContent().read(act);
final String s = new String(act).trim();
assertTrue(s.contains("\"FullName\":\"Wunder, Willi\""));
}
@Test
void testRepresentationResponseContentMapResult() throws ODataException, IOException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy());
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
final byte[] act = new byte[100];
response.getContent().read(act);
final String s = new String(act).trim();
assertEquals("{\"ID\":\"35\"}", s);
}
@Test
void testRepresentationLocationHeader() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy());
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION));
}
@Test
void testRepresentationLocationHeaderMapResult() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy());
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION));
}
@Test
void testCallsValidateChangesOnSuccessfulProcessing() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(1, spy.noValidateCalls);
}
@Test
void testDoesNotCallsValidateChangesOnForeignTransaction() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(factory.hasActiveTransaction()).thenReturn(Boolean.TRUE);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(0, spy.noValidateCalls);
}
@Test
void testDoesNotCallsValidateChangesOnError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).createEntity(any(JPARequestEntity.class), any(EntityManager.class));
assertThrows(ODataApplicationException.class,
() -> processor.createEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(handler, never()).validateChanges(em);
}
@Test
void testDoesRollbackIfValidateRaisesError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em);
assertThrows(ODataApplicationException.class,
() -> processor.createEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testDoesRollbackIfCreateRaisesArbitraryError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new RuntimeException("Test")).when(handler).createEntity(any(), any());
assertThrows(ODataApplicationException.class,
() -> processor.createEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testDoesRollbackOnWrongResponse() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final String result = "";
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
when(handler.createEntity(any(), any())).thenReturn(result);
assertThrows(ODataException.class,
() -> processor.createEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testOwnTransactionCommitted() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
verify(transaction, times(1)).commit();
}
@Test
void testResponseCreateChildSameTypeContent() throws ODataException {
when(ets.getName()).thenReturn("AdministrativeDivisions");
final AdministrativeDivision div = new AdministrativeDivision(new AdministrativeDivisionKey("Eurostat", "NUTS1",
"DE6"));
final AdministrativeDivision child = new AdministrativeDivision(new AdministrativeDivisionKey("Eurostat", "NUTS2",
"DE60"));
div.getChildren().add(child);
final RequestHandleSpy spy = new RequestHandleSpy(div);
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRequestToCreateChild(spy);
final UriResourceNavigation uriChild = mock(UriResourceNavigation.class);
final List<UriParameter> uriKeys = new ArrayList<>();
final EdmNavigationProperty naviProperty = mock(EdmNavigationProperty.class);
createKeyPredicate(uriKeys, "DivisionCode", "DE6");
createKeyPredicate(uriKeys, "CodeID", "NUTS1");
createKeyPredicate(uriKeys, "CodePublisher", "Eurostat");
when(uriChild.getKind()).thenReturn(UriResourceKind.navigationProperty);
when(uriChild.getProperty()).thenReturn(naviProperty);
when(naviProperty.getName()).thenReturn("Children");
when(uriEts.getKeyPredicates()).thenReturn(uriKeys);
when(convHelper.convertUriKeys(any(), any(), any())).thenCallRealMethod();
when(convHelper.buildGetterMap(div)).thenReturn(new JPAConversionHelper().determineGetter(div));
when(convHelper.buildGetterMap(child)).thenReturn(new JPAConversionHelper().determineGetter(child));
pathParts.add(uriChild);
processor = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, convHelper);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.requestEntity.getKeys());
assertEquals("DE6", spy.requestEntity.getKeys().get("divisionCode"));
assertNotNull(spy.requestEntity.getRelatedEntities());
for (final Entry<JPAAssociationPath, List<JPARequestEntity>> c : spy.requestEntity.getRelatedEntities().entrySet())
assertEquals("Children", c.getKey().getAlias());
}
@Test
void testResponseCreateChildDifferentTypeContent() throws ODataException {
final Organization org = new Organization("Test");
final BusinessPartnerRole role = new BusinessPartnerRole();
role.setBusinessPartner(org);
role.setRoleCategory("A");
org.getRoles().add(role);
final RequestHandleSpy spy = new RequestHandleSpy(org);
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRequestToCreateChild(spy);
final UriResourceNavigation uriChild = mock(UriResourceNavigation.class);
final List<UriParameter> uriKeys = new ArrayList<>();
final EdmNavigationProperty naviProperty = mock(EdmNavigationProperty.class);
final EdmNavigationPropertyBinding naviBinding = mock(EdmNavigationPropertyBinding.class);
final EdmEntityContainer container = mock(EdmEntityContainer.class);
final List<EdmNavigationPropertyBinding> naviBindings = new ArrayList<>(0);
final EdmEntitySet targetEts = mock(EdmEntitySet.class);
naviBindings.add(naviBinding);
createKeyPredicate(uriKeys, "ID", "Test");
when(uriChild.getKind()).thenReturn(UriResourceKind.navigationProperty);
when(uriChild.getProperty()).thenReturn(naviProperty);
when(naviProperty.getName()).thenReturn("Roles");
when(uriEts.getKeyPredicates()).thenReturn(uriKeys);
when(convHelper.convertUriKeys(any(), any(), any())).thenCallRealMethod();
when(convHelper.buildGetterMap(org)).thenReturn(new JPAConversionHelper().determineGetter(org));
when(convHelper.buildGetterMap(role)).thenReturn(new JPAConversionHelper().determineGetter(role));
when(ets.getNavigationPropertyBindings()).thenReturn(naviBindings);
when(naviBinding.getPath()).thenReturn("Roles");
when(naviBinding.getTarget()).thenReturn("BusinessPartnerRoles");
when(ets.getEntityContainer()).thenReturn(container);
when(container.getEntitySet("BusinessPartnerRoles")).thenReturn(targetEts);
final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.BusinessPartnerRole");
final List<String> keyNames = Arrays.asList("BusinessPartnerID", "RoleCategory");
final Edm edm = mock(Edm.class);
final EdmEntityType edmET = mock(EdmEntityType.class);
when(serviceMetadata.getEdm()).thenReturn(edm);
when(edm.getEntityType(fqn)).thenReturn(edmET);
when(edmET.getKeyPredicateNames()).thenReturn(keyNames);
createKeyProperty(fqn, edmET, "BusinessPartnerID", "Test");
createKeyProperty(fqn, edmET, "RoleCategory", "A");
pathParts.add(uriChild);
processor = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, convHelper);
processor.createEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.requestEntity.getKeys());
assertEquals("Test", spy.requestEntity.getKeys().get("iD"));
assertNotNull(spy.requestEntity.getRelatedEntities());
for (final Entry<JPAAssociationPath, List<JPARequestEntity>> c : spy.requestEntity.getRelatedEntities().entrySet())
assertEquals("Roles", c.getKey().getAlias());
}
protected ODataRequest prepareRequestToCreateChild(final JPAAbstractCUDRequestHandler spy)
throws ODataException {
// .../AdministrativeDivisions(DivisionCode='DE6',CodeID='NUTS1',CodePublisher='Eurostat')/Children
final ODataRequest request = prepareSimpleRequest("return=representation");
final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision");
final List<String> keyNames = Arrays.asList("DivisionCode", "CodeID", "CodePublisher");
final Edm edm = mock(Edm.class);
final EdmEntityType edmET = mock(EdmEntityType.class);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(serviceMetadata.getEdm()).thenReturn(edm);
when(edm.getEntityType(fqn)).thenReturn(edmET);
when(edmET.getKeyPredicateNames()).thenReturn(keyNames);
createKeyProperty(fqn, edmET, "DivisionCode", "DE6");
createKeyProperty(fqn, edmET, "CodeID", "NUTS1");
createKeyProperty(fqn, edmET, "CodePublisher", "Eurostat");
createKeyProperty(fqn, edmET, "DivisionCode", "DE60");
createKeyProperty(fqn, edmET, "CodeID", "NUTS2");
createKeyProperty(fqn, edmET, "CodePublisher", "Eurostat");
when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(JPAEntityCollectionExtension.class)))
.thenReturn(
serializerResult);
when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ID\":\"35\"}".getBytes()));
return request;
}
private void createKeyPredicate(final List<UriParameter> uriKeys, final String name, final String value) {
final UriParameter key = mock(UriParameter.class);
uriKeys.add(key);
when(key.getName()).thenReturn(name);
when(key.getText()).thenReturn("'" + value + "'");
}
private void createKeyProperty(final FullQualifiedName fqn, final EdmEntityType edmET, final String name,
final String value)
throws EdmPrimitiveTypeException {
final EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class);
when(edmET.getKeyPropertyRef(name)).thenReturn(refType);
when(edmET.getFullQualifiedName()).thenReturn(fqn);
final EdmProperty edmProperty = mock(EdmProperty.class);
when(refType.getProperty()).thenReturn(edmProperty);
when(refType.getName()).thenReturn(name);
final EdmPrimitiveType type = mock(EdmPrimitiveType.class);
when(edmProperty.getType()).thenReturn(type);
when(type.valueToString(ArgumentMatchers.eq(value), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers
.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(value);
when(type.toUriLiteral(ArgumentMatchers.anyString())).thenReturn(value);
}
private EdmProperty createProperty(final String name, final EdmType propertyType) {
final EdmProperty property = mock(EdmProperty.class);
when(property.isPrimitive()).thenReturn(true);
when(property.getType()).thenReturn(propertyType);
when(property.getName()).thenReturn(name);
when(property.isNullable()).thenReturn(true);
when(property.getMaxLength()).thenReturn(255);
return property;
}
class RequestHandleSpy extends JPAAbstractCUDRequestHandler {
public int noValidateCalls;
public JPAEntityType et;
public Map<String, Object> jpaAttributes;
public EntityManager em;
public boolean called = false;
public Map<String, List<String>> headers;
public JPARequestEntity requestEntity;
private final Object result;
public Optional<JPAODataClaimProvider> claims;
public List<String> groups;
RequestHandleSpy(final Object result) {
this.result = result;
}
RequestHandleSpy() {
this.result = new Organization();
((Organization) result).setID("35");
}
@Override
public Object createEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessException {
this.et = requestEntity.getEntityType();
this.jpaAttributes = requestEntity.getData();
this.em = em;
this.headers = requestEntity.getAllHeader();
this.called = true;
this.requestEntity = requestEntity;
this.claims = requestEntity.getClaims();
this.groups = requestEntity.getGroups();
return result;
}
@Override
public void validateChanges(final EntityManager em) throws ODataJPAProcessException {
this.noValidateCalls++;
}
}
class RequestHandleMapResultSpy extends JPAAbstractCUDRequestHandler {
public JPAEntityType et;
public Map<String, Object> jpaAttributes;
public EntityManager em;
public boolean called = false;
public JPARequestEntity requestEntity;
@Override
public Object createEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessException {
final Map<String, Object> result = new HashMap<>();
result.put("iD", "35");
this.et = requestEntity.getEntityType();
this.jpaAttributes = requestEntity.getData();
this.em = em;
this.called = true;
this.requestEntity = requestEntity;
return result;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.sql.DataSource;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import org.apache.olingo.commons.api.data.ComplexValue;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.data.EntityCollection;
import org.apache.olingo.commons.api.data.Link;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.JPAReferences;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
import com.sap.olingo.jpa.processor.core.query.EdmBindingTargetInfo;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.util.TestBase;
class TestCreateRequestEntity {
protected static final String ENTITY_SET_NAME = "AdministrativeDivisions";
protected static final String ENTITY_TYPE_NAME = "AdministrativeDivision";
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
protected static EntityManagerFactory emf;
protected static JPAEdmProvider jpaEdm;
protected static DataSource dataSource;
protected static List<AnnotationProvider> annotationProvider;
protected static JPAReferences references;
protected static EdmBindingTargetInfo targetInfo;
@BeforeAll
public static void setupClass() throws ODataException {
final JPAEdmMetadataPostProcessor postProcessor = mock(JPAEdmMetadataPostProcessor.class);
targetInfo = mock(EdmBindingTargetInfo.class);
annotationProvider = new ArrayList<>();
dataSource = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, dataSource);
jpaEdm = new JPAEdmProvider(PUNIT_NAME, emf.getMetamodel(), postProcessor, TestBase.enumPackages,
annotationProvider);
}
private OData odata;
private JPACUDRequestProcessor cut;
private Entity oDataEntity;
private ServiceMetadata serviceMetadata;
private JPAODataRequestContextAccess requestContext;
private UriInfo uriInfo;
private UriResourceEntitySet uriEs;
private EntityManager em;
private EntityTransaction transaction;
private JPASerializer serializer;
private EdmEntitySet es;
private List<UriParameter> keyPredicates;
private JPAConversionHelper convHelper;
private final List<UriResource> pathParts = new ArrayList<>();
private Map<String, List<String>> headers;
@BeforeEach
void setUp() throws Exception {
odata = OData.newInstance();
requestContext = mock(JPAODataRequestContextAccess.class);
serviceMetadata = mock(ServiceMetadata.class);
uriInfo = mock(UriInfo.class);
keyPredicates = new ArrayList<>();
es = mock(EdmEntitySet.class);
serializer = mock(JPASerializer.class);
uriEs = mock(UriResourceEntitySet.class);
pathParts.add(uriEs);
convHelper = new JPAConversionHelper();// mock(JPAConversionHelper.class);
em = mock(EntityManager.class);
transaction = mock(EntityTransaction.class);
headers = new HashMap<>(0);
when(requestContext.getEdmProvider()).thenReturn(jpaEdm);
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getUriInfo()).thenReturn(uriInfo);
when(requestContext.getSerializer()).thenReturn(serializer);
when(uriInfo.getUriResourceParts()).thenReturn(pathParts);
when(uriEs.getKeyPredicates()).thenReturn(keyPredicates);
when(uriEs.getEntitySet()).thenReturn(es);
when(uriEs.getKind()).thenReturn(UriResourceKind.entitySet);
when(es.getName()).thenReturn(ENTITY_SET_NAME);
when(em.getTransaction()).thenReturn(transaction);
when(targetInfo.getEdmBindingTarget()).thenReturn(es);
when(targetInfo.getName()).thenReturn(ENTITY_SET_NAME);
when(targetInfo.getKeyPredicates()).thenReturn(Collections.emptyList());
cut = new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, convHelper);
}
@Test
void testCreateDataAndEtCreated() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
assertNotNull(act.getData());
assertNotNull(act.getEntityType());
}
@Test
void testCreateEtName() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
assertEquals(ENTITY_TYPE_NAME, act.getEntityType().getExternalName());
}
@Test
void testCreateDataHasProperty() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final String actValue = (String) act.getData().get("codeID");
assertNotNull(actValue);
assertEquals("DE50", actValue);
}
@Test
void testCreateEmptyRelatedEntities() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
assertNotNull(act.getRelatedEntities());
assertTrue(act.getRelatedEntities().isEmpty());
}
@Test
void testCreateEmptyRelationLinks() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
assertNotNull(act.getRelationLinks());
assertTrue(act.getRelationLinks().isEmpty());
}
@Test
void testCreateDeepOneChildResultContainsEntityLink() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final List<Link> navigationLinks = new ArrayList<>();
addChildrenNavigationLinkDE501(navigationLinks);
when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findEntryList(act.getRelatedEntities(), ("children"));
assertNotNull(actValue, "Is null");
assertTrue(actValue instanceof List, "Wrong type");
}
@Test
void testCreateDeepOneChildResultContainsEntityLinkSize() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final List<Link> navigationLinks = new ArrayList<>();
addChildrenNavigationLinkDE501(navigationLinks);
when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findEntryList(act.getRelatedEntities(), ("children"));
assertEquals(1, ((List<?>) actValue).size(), "Wrong size");
}
@Test
void testCreateDeepOneChildResultContainsEntityLinkEntityType() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final List<Link> navigationLinks = new ArrayList<>();
addChildrenNavigationLinkDE501(navigationLinks);
when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findEntryList(act.getRelatedEntities(), ("children"));
assertNotNull(((List<?>) actValue).get(0));
assertNotNull(((JPARequestEntity) ((List<?>) actValue).get(0)).getEntityType(), "Entity type not found");
assertEquals("AdministrativeDivision", ((JPARequestEntity) ((List<?>) actValue).get(0))
.getEntityType().getExternalName(), "Wrong Type");
}
@Test
void testCreateDeepOneChildResultContainsEntityLinkData() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final List<Link> navigationLinks = new ArrayList<>();
addChildrenNavigationLinkDE501(navigationLinks);
when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findEntryList(act.getRelatedEntities(), ("children"));
assertNotNull(((List<?>) actValue).get(0));
assertNotNull(((JPARequestEntity) ((List<?>) actValue).get(0)).getEntityType(), "Entity type not found");
final Map<String, Object> actData = ((JPARequestEntity) ((List<?>) actValue).get(0)).getData();
assertNotNull(actData, "Data not found");
assertNotNull(actData.get("codeID"), "CodeID not found");
assertEquals("DE501", actData.get("codeID"), "Value not found");
}
@Test
void testCreateDeepTwoChildResultContainsEntityLinkSize() throws ODataException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final List<Link> navigationLinks = new ArrayList<>();
addNavigationLinkDE502(navigationLinks);
when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findEntryList(act.getRelatedEntities(), ("children"));
assertEquals(2, ((List<?>) actValue).size(), "Wrong size");
}
@Test
void testCreateWithLinkToOne() throws ODataJPAProcessorException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final List<Link> bindingLinks = new ArrayList<>();
addParentBindingLink(bindingLinks);
when(oDataEntity.getNavigationBindings()).thenReturn(bindingLinks);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findLinkList(act.getRelationLinks(), ("parent"));
assertNotNull(actValue);
assertTrue(actValue instanceof List<?>);
}
@Test
void testCreateWithLinkToMany() throws ODataJPAProcessorException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final List<Link> bindingLinks = new ArrayList<>();
addChildrenBindingLink(bindingLinks);
when(oDataEntity.getNavigationBindings()).thenReturn(bindingLinks);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findLinkList(act.getRelationLinks(), ("children"));
assertNotNull(actValue);
assertTrue(actValue instanceof List<?>);
assertEquals(2, ((List<?>) actValue).size());
}
@Test
void testCreateDeepToOne() throws ODataJPAProcessorException {
final List<Property> properties = createProperties();
createODataEntity(properties);
final List<Link> navigationLinks = new ArrayList<>();
final Link navigationLink = addParentNavigationLink(navigationLinks);
when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks);
when(oDataEntity.getNavigationLink("Parent")).thenReturn(navigationLink);
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findEntryList(act.getRelatedEntities(), ("parent"));
assertNotNull(actValue);
assertTrue(actValue instanceof List<?>);
}
@Test
void testCreateOrganizationWithRoles() throws ODataJPAProcessorException {
final List<Property> properties = new ArrayList<>();
createPropertyBuPaID(properties, "20");
createODataEntity(properties);
//-----------------------------
final List<Link> navigationLinks = new ArrayList<>();
final Link navigationLink = mock(Link.class);
when(navigationLink.getTitle()).thenReturn("Roles");
navigationLinks.add(navigationLink);
final EntityCollection navigationEntitySet = mock(EntityCollection.class);
final List<Entity> entityCollection = new ArrayList<>();
final Entity navigationEntity1 = mock(Entity.class);
final List<Property> navigationEntityProperties1 = createPropertiesRoles("20", "A");
when(navigationEntity1.getProperties()).thenReturn(navigationEntityProperties1);//
entityCollection.add(navigationEntity1);
final Entity navigationEntity2 = mock(Entity.class);
final List<Property> navigationEntityProperties2 = createPropertiesRoles("20", "C");
when(navigationEntity2.getProperties()).thenReturn(navigationEntityProperties2);//
entityCollection.add(navigationEntity2);
when(navigationEntitySet.getEntities()).thenReturn(entityCollection);
when(navigationLink.getInlineEntitySet()).thenReturn(navigationEntitySet);
when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks);
when(oDataEntity.getNavigationLink("Roles")).thenReturn(navigationLink);
//------------------------------------
when(es.getName()).thenReturn("Organizations");
when(targetInfo.getName()).thenReturn("Organizations");
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
assertNotNull(act);
assertNotNull(act.getData());
assertNotNull(findEntryList(act.getRelatedEntities(), ("roles")));
}
@Test
void testCreateDeepOneChildViaComplex() throws ODataException {
final List<Property> properties = new ArrayList<>();
final List<Property> inlineProperties = new ArrayList<>();
final Entity inlineEntity = mock(Entity.class);
createODataEntity(properties);
when(targetInfo.getName()).thenReturn("Persons");
when(es.getName()).thenReturn("Persons");
createPropertyBuPaID(properties, "20");
when(inlineEntity.getProperties()).thenReturn(inlineProperties);
createPropertyBuPaID(inlineProperties, "200");
final List<Property> adminProperties = createComplexProperty(properties, "AdministrativeInformation", null, null,
oDataEntity);
final List<Property> createdProperties = createComplexProperty(adminProperties, "Created", "User", inlineEntity,
oDataEntity);
createPrimitiveProperty(createdProperties, "99", "By");
createPrimitiveProperty(createdProperties, Timestamp.valueOf("2016-01-20 09:21:23.0"), "At");
final JPARequestEntity act = cut.createRequestEntity(targetInfo, oDataEntity, headers);
final Object actValue = findEntryList(act.getRelatedEntities(), ("administrativeInformation"));
assertNotNull(actValue);
assertNotNull(((List<?>) actValue).get(0));
@SuppressWarnings("unchecked")
final JPARequestEntity actDeepEntity = ((List<JPARequestEntity>) actValue).get(0);
assertEquals("200", actDeepEntity.getData().get("iD"));
}
private List<Property> createComplexProperty(final List<Property> properties, final String name, final String target,
final Entity inlineEntity, final Entity oDataEntity) {
final Property property = mock(Property.class);
final ComplexValue cv = mock(ComplexValue.class);
final List<Property> cProperties = new ArrayList<>();
final Link navigationLink = mock(Link.class);
when(property.getName()).thenReturn(name);
when(property.getValue()).thenReturn(cv);
when(property.getValueType()).thenReturn(ValueType.COMPLEX);
when(property.isComplex()).thenReturn(true);
when(property.asComplex()).thenReturn(cv);
when(cv.getValue()).thenReturn(cProperties);
when(cv.getNavigationLink(target)).thenReturn(navigationLink);
when(navigationLink.getInlineEntity()).thenReturn(inlineEntity);
when(oDataEntity.getProperty(name)).thenReturn(property);
properties.add(property);
return cProperties;
}
private Link addParentNavigationLink(final List<Link> navigationLinks) {
final Link navigationLink = mock(Link.class);
when(navigationLink.getTitle()).thenReturn("Parent");
navigationLinks.add(navigationLink);
final Entity navigationEntity = mock(Entity.class);
when(navigationLink.getInlineEntity()).thenReturn(navigationEntity);
final List<Property> navigationEntityProperties = createPropertyCodeID("DE5");
when(navigationEntity.getProperties()).thenReturn(navigationEntityProperties);//
return navigationLink;
}
private void addParentBindingLink(final List<Link> bindingLinks) {
final Link bindingLink = mock(Link.class);
when(bindingLink.getTitle()).thenReturn("Parent");
bindingLinks.add(bindingLink);
when(bindingLink.getBindingLink()).thenReturn(
"AdministrativeDivisions(DivisionCode='DE1',CodeID='NUTS1',CodePublisher='Eurostat')");
}
private void addChildrenNavigationLinkDE501(final List<Link> navigationLinks) {
addChildrenNavigationLink(navigationLinks, "DE501", null);
}
private void addNavigationLinkDE502(final List<Link> navigationLinks) {
addChildrenNavigationLink(navigationLinks, "DE501", "DE502");
}
private void addChildrenNavigationLink(final List<Link> navigationLinks, final String codeValue1,
final String codeValue2) {
final Link navigationLink = mock(Link.class);
when(navigationLink.getTitle()).thenReturn("Children");
navigationLinks.add(navigationLink);
final EntityCollection navigationEntitySet = mock(EntityCollection.class);
final List<Entity> entityCollection = new ArrayList<>();
final Entity navigationEntity1 = mock(Entity.class);
final List<Property> navigationEntityProperties1 = createPropertyCodeID(codeValue1);
when(navigationEntity1.getProperties()).thenReturn(navigationEntityProperties1);//
entityCollection.add(navigationEntity1);
if (codeValue2 != null) {
final Entity navigationEntity2 = mock(Entity.class);
final List<Property> navigationEntityProperties2 = createPropertyCodeID(codeValue2);
when(navigationEntity2.getProperties()).thenReturn(navigationEntityProperties2);//
entityCollection.add(navigationEntity2);
}
when(navigationEntitySet.getEntities()).thenReturn(entityCollection);
when(navigationLink.getInlineEntitySet()).thenReturn(navigationEntitySet);
when(oDataEntity.getNavigationLink("Children")).thenReturn(navigationLink);
}
private void addChildrenBindingLink(final List<Link> bindingLinks) {
final List<String> links = new ArrayList<>();
final Link bindingLink = mock(Link.class);
when(bindingLink.getTitle()).thenReturn("Children");
bindingLinks.add(bindingLink);
when(bindingLink.getBindingLinks()).thenReturn(links);
links.add("AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')");
links.add("AdministrativeDivisions(DivisionCode='DE101',CodeID='NUTS3',CodePublisher='Eurostat')");
}
private void createODataEntity(final List<Property> properties) {
oDataEntity = mock(Entity.class);
when(oDataEntity.getProperties()).thenReturn(properties);
}
private List<Property> createProperties() {
return createPropertyCodeID("DE50");
}
private List<Property> createPropertyCodeID(final String codeID) {
final List<Property> properties = new ArrayList<>();
createPrimitiveProperty(properties, codeID, "CodeID");
return properties;
}
private void createPropertyBuPaID(final List<Property> properties, final String value) {
createPrimitiveProperty(properties, value, "ID");
}
private void createPrimitiveProperty(final List<Property> properties, final Object value, final String name) {
final Property property = mock(Property.class);
when(property.getName()).thenReturn(name);
when(property.getValue()).thenReturn(value);
when(property.getValueType()).thenReturn(ValueType.PRIMITIVE);
properties.add(property);
}
private List<Property> createPropertiesRoles(final String BuPaId, final String RoleCategory) {
final List<Property> properties = new ArrayList<>();
createPrimitiveProperty(properties, BuPaId, "BusinessPartnerID");
createPrimitiveProperty(properties, RoleCategory, "RoleCategory");
return properties;
}
private Object findEntryList(final Map<JPAAssociationPath, List<JPARequestEntity>> relatedEntities,
final String associationName) {
for (final Entry<JPAAssociationPath, List<JPARequestEntity>> entity : relatedEntities.entrySet()) {
if (entity.getKey().getPath().get(0).getInternalName().equals(associationName))
return entity.getValue();
}
return null;
}
private Object findLinkList(final Map<JPAAssociationPath, List<JPARequestLink>> relationLink,
final String associationName) {
for (final Entry<JPAAssociationPath, List<JPARequestLink>> entity : relationLink.entrySet()) {
if (entity.getKey().getPath().get(0).getInternalName().equals(associationName))
return entity.getValue();
}
return null;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPACoreDebuggerTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPACoreDebuggerTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.server.api.debug.RuntimeMeasurement;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
class JPACoreDebuggerTest {
private JPACoreDebugger cutDebugOn;
private JPACoreDebugger cutDebugOff;
private static LogHandler logHandler;
private PrintStream systemOut;
private OutputStream output;
private PrintStream printOut;
@BeforeAll
static void classSetup() {
// Redirect log to System out
System.getProperties().put("org.slf4j.simpleLogger.logFile", "System.err");
System.getProperties().put(
"org.slf4j.simpleLogger.log.com.sap.olingo.jpa.processor.core.processor.JPACoreDebuggerTest", "debug");
System.getProperties().put("org.slf4j.simpleLogger.log.com.sap.olingo.jpa.processor.core.processor.JPACoreDebugger",
"trace");
logHandler = new LogHandler();
Logger.getLogger("com.sap.olingo.jpa.processor.core.processor.TestJPACoreDebugger").setLevel(Level.FINE);
Logger.getLogger("com.sap.olingo.jpa.processor.core.processor.TestJPACoreDebugger").addHandler(logHandler);
Logger.getLogger("com.sap.olingo.jpa.processor.core.processor.JPACoreDebugger").setLevel(Level.FINEST);
Logger.getLogger("com.sap.olingo.jpa.processor.core.processor.JPACoreDebugger").addHandler(logHandler);
}
@BeforeEach
void setup() {
cutDebugOn = new JPACoreDebugger(true);
cutDebugOff = new JPACoreDebugger(false);
systemOut = System.err;
output = new ByteArrayOutputStream();
printOut = new PrintStream(output);
}
@AfterEach
void teardown() {
logHandler.close();
System.setErr(systemOut);
}
@Test
void testMeasurementCreated() {
try (JPARuntimeMeasurement measurement = cutDebugOn.newMeasurement(cutDebugOn, "firstTest")) {}
assertFalse(cutDebugOn.getRuntimeInformation().isEmpty());
}
@Test
void testNoMeasurementDebugFalls() {
cutDebugOn = new JPACoreDebugger(false);
try (JPARuntimeMeasurement measurement = cutDebugOn.newMeasurement(cutDebugOn, "firstTest")) {}
assertTrue(cutDebugOn.getRuntimeInformation().isEmpty());
}
@Test
void testMeasurementCreateMeasurement() throws Exception {
try (JPARuntimeMeasurement measurement = cutDebugOn.newMeasurement(cutDebugOn, "firstTest")) {
TimeUnit.MILLISECONDS.sleep(100);
}
assertFalse(cutDebugOn.getRuntimeInformation().isEmpty());
final RuntimeMeasurement act = cutDebugOn.getRuntimeInformation().get(0);
final long delta = act.getTimeStopped() - act.getTimeStarted();
assertTrue(delta >= 100);
assertEquals("firstTest", act.getMethodName());
assertEquals(cutDebugOn.getClass().getName(), act.getClassName());
}
@Test
void testRuntimeMeasurementEmptyAfterStopWhenOff() throws InterruptedException {
System.setErr(printOut);
try (JPARuntimeMeasurement measurement = cutDebugOn.newMeasurement(cutDebugOn, "firstTest")) {
TimeUnit.MILLISECONDS.sleep(10);
}
final String act = output.toString();
assertTrue(cutDebugOff.getRuntimeInformation().isEmpty());
assertTrue(StringUtils.isNotEmpty(act));
}
@SuppressWarnings("resource")
@Test
void testMemoryMeasurement() {
final JPARuntimeMeasurement measurement;
try (final JPARuntimeMeasurement m = cutDebugOn.newMeasurement(cutDebugOn, "firstTest")) {
@SuppressWarnings("unused")
final String[] dummy = new String[100];
measurement = m;
}
assertTrue(measurement.getMemoryConsumption() > 0);
}
@Test
void testDebugLogWithTread() {
System.setErr(printOut);
cutDebugOff.debug(this, "Test");
final String act = output.toString();
assertTrue(StringUtils.isNotEmpty(act));
assertTrue(act.contains("thread"));
}
@Test
void testDebugLogText() {
System.setErr(printOut);
cutDebugOff.debug(this, "Test %s", "Hallo");
final String act = output.toString();
assertTrue(StringUtils.isNotEmpty(act));
assertTrue(act.contains("thread"));
assertTrue(act.contains("Hallo"));
}
@Test
void testDebugHasNoTrace() {
System.setErr(printOut);
cutDebugOff.trace(this, "Test");
final String act = output.toString();
assertTrue(StringUtils.isEmpty(act));
}
@Test
void testTraceLogText() {
System.setErr(printOut);
cutDebugOff.trace(cutDebugOff, "Test %s", "Hallo");
final String act = output.toString();
assertTrue(StringUtils.isNotEmpty(act));
assertTrue(act.contains("thread"));
assertTrue(act.contains("Hallo"));
}
@SuppressWarnings("resource")
@Test
void testMemoryConsumption() {
final JPARuntimeMeasurement act;
try (JPARuntimeMeasurement measurement = cutDebugOn.newMeasurement(cutDebugOn, "firstTest")) {
act = measurement;
} finally {
}
assertTrue(act.getMemoryConsumption() < 10);
}
private static class LogHandler extends Handler {
private List<LogRecord> cache = new ArrayList<>();
@Override
public void publish(final LogRecord record) {
cache.add(record);
}
@Override
public void flush() {
// Do nothing
}
@Override
public void close() throws SecurityException {
cache = new ArrayList<>();
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAExpandWatchDogTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAExpandWatchDogTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlDynamicExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyValue;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlRecord;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.LevelsExpandOption;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.util.AbstractWatchDogTest;
import com.sap.olingo.jpa.processor.core.util.ExpandOptionDouble;
class JPAExpandWatchDogTest extends AbstractWatchDogTest {
private static final String ES_EXTERNAL_NAME = "Organizations";
private JPAExpandWatchDog cut;
@Test
void testCanCreateInstanceWithoutAnnotatable() throws ODataJPAProcessException {
assertNotNull(new JPAExpandWatchDog(Optional.empty()));
}
private static Stream<Arguments> provideIsExpandable() {
return Stream.of(
Arguments.of(Optional.empty(), true),
Arguments.of(createAnnotatable(false, -1), false),
Arguments.of(createAnnotatable(true, -1), true),
Arguments.of(createAnnotatable(null, -1), true));
}
@ParameterizedTest
@MethodSource("provideIsExpandable")
void testIsExpandable(final Optional<JPAAnnotatable> annotatable, final boolean exp)
throws ODataJPAProcessException {
cut = new JPAExpandWatchDog(annotatable);
assertEquals(exp, cut.isExpandable());
}
private static Stream<Arguments> provideRemainingLevels() {
return Stream.of(
Arguments.of(Optional.empty(), Integer.MAX_VALUE),
Arguments.of(createAnnotatable(true, -1), Integer.MAX_VALUE),
Arguments.of(createAnnotatable(true, -7), Integer.MAX_VALUE),
Arguments.of(createAnnotatable(true, 0), 0),
Arguments.of(createAnnotatable(true, 3), 3),
Arguments.of(createAnnotatable(true, null), Integer.MAX_VALUE));
}
@ParameterizedTest
@MethodSource("provideRemainingLevels")
void testRemainingLevels(final Optional<JPAAnnotatable> annotatable, final Integer exp)
throws ODataJPAProcessException {
cut = new JPAExpandWatchDog(annotatable);
assertEquals(exp, cut.getRemainingLevels());
}
private static Stream<Arguments> provideSimpleChecks() {
return Stream.of(
Arguments.of(createAnnotatable(true, -1)),
Arguments.of(createAnnotatable(false, -1)));
}
@ParameterizedTest
@MethodSource("provideSimpleChecks")
void testWatchChecksExpandOptNonNull(final Optional<JPAAnnotatable> annotatable)
throws ODataJPAProcessException {
cut = new JPAExpandWatchDog(annotatable);
assertDoesNotThrow(() -> cut.watch(null, null));
}
@ParameterizedTest
@MethodSource("provideSimpleChecks")
void testWatchChecksExpandOptionWithoutItems(final Optional<JPAAnnotatable> annotatable)
throws ODataJPAProcessException {
final ExpandOption expandOption = new ExpandOptionDouble("", Collections.emptyList());
cut = new JPAExpandWatchDog(annotatable);
assertDoesNotThrow(() -> cut.watch(expandOption, emptyList()));
}
@Test
void testWatchChecksExpandNotSupported() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(false, -1, "Children");
final ExpandItem expandItem = createExpandItem("Parent");
final ExpandOption expandOption = new ExpandOptionDouble("", Collections.singletonList(expandItem));
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, emptyList()));
}
@Test
void testWatchChecksOneExpandAllowed() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, -1, "Children");
final ExpandItem expandItem = createExpandItem("Parent");
final ExpandOption expandOption = new ExpandOptionDouble("", Collections.singletonList(expandItem));
cut = new JPAExpandWatchDog(annotatable);
assertDoesNotThrow(() -> cut.watch(expandOption, queryPathOnlyRoot()));
}
private static Stream<Arguments> provideOneExpandNotAllowed() {
return Stream.of(
Arguments.of(createAnnotatable(true, -1, "Parent"), new String[] { "Parent" }),
Arguments.of(createAnnotatable(true, -1, "Parent/Parent"), new String[] { "Parent", "Parent" }));
}
@ParameterizedTest
@MethodSource("provideOneExpandNotAllowed")
void testWatchChecksOneExpandNotAllowed(final Optional<JPAAnnotatable> annotatable, final String[] expandPaths)
throws ODataJPAProcessException {
final ExpandItem expandItem = createExpandItem(expandPaths);
final ExpandOption expandOption = new ExpandOptionDouble("", Collections.singletonList(expandItem));
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksOneOfMultipleExpandNotAllowed() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, -1, "Parent");
final ExpandItem expandItemChildren = createExpandItem("Children");
final ExpandItem expandItemParent = createExpandItem("Parent");
final ExpandItem expandItemSibling = createExpandItem("Silbling");
final ExpandOption expandOption = new ExpandOptionDouble("",
Arrays.asList(expandItemChildren, expandItemParent, expandItemSibling));
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchDoesNotCheckStar() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, -1, "Parent");
final ExpandItem expandItem = mock(ExpandItem.class);
when(expandItem.isStar()).thenReturn(Boolean.TRUE);
final ExpandOption expandOption = new ExpandOptionDouble("", singletonList(expandItem));
cut = new JPAExpandWatchDog(annotatable);
assertDoesNotThrow(() -> cut.watch(expandOption, queryPathOnlyRoot()));
}
private static Stream<Arguments> provideNonExpandableProperties() {
return Stream.of(
Arguments.of(Optional.empty(), Collections.emptyList()),
Arguments.of(createAnnotatable(true, -1, "Parent"), Arrays.asList("Parent")),
Arguments.of(createAnnotatable(true, -1), Collections.emptyList()));
}
@ParameterizedTest
@MethodSource("provideNonExpandableProperties")
void testNonExpandableProperties(final Optional<JPAAnnotatable> annotatable, final List<String> exp)
throws ODataJPAProcessException {
cut = new JPAExpandWatchDog(annotatable);
assertEquals(exp, cut.getNonExpandableProperties());
}
@Test
void testWatchChecksOneExpandViaNavigationNotAllowed() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, -1,
"AdministrativeInformation/CreatedBy/User");
final ExpandItem expandItem = createExpandItem("CreatedBy", "User");
final ExpandOption expandOption = new ExpandOptionDouble("", Collections.singletonList(expandItem));
final UriResource esUriResource = mock(UriResource.class);
when(esUriResource.getSegmentValue()).thenReturn(ES_EXTERNAL_NAME);
final UriResource complexUriResource = mock(UriResource.class);
when(complexUriResource.getSegmentValue()).thenReturn("AdministrativeInformation");
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption,
Arrays.asList(esUriResource, complexUriResource)));
}
@Test
void testWatchChecksOneExpandLevelBelowMaxLevel() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem = createExpandItem("Parent");
final ExpandOption expandOption = new ExpandOptionDouble("", Collections.singletonList(expandItem));
cut = new JPAExpandWatchDog(annotatable);
assertDoesNotThrow(() -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksOneExpandLevelAboveMaxLevel1() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 1);
final ExpandItem expandItem = createExpandItem("Parent");
final ExpandOption expandOption = new ExpandOptionDouble("", singletonList(expandItem));
final ExpandItem secondExpandItem = createExpandItem("Parent");
final ExpandOption secondExpandOption = new ExpandOptionDouble("", singletonList(secondExpandItem));
when(expandItem.getExpandOption()).thenReturn(secondExpandOption);
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksOneExpandLevelAboveMaxLevel2() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem = createExpandItem("Parent");
final ExpandOption expandOption = new ExpandOptionDouble("", singletonList(expandItem));
final ExpandItem secondExpandItem = createExpandItem("Parent");
final ExpandOption secondExpandOption = new ExpandOptionDouble("", singletonList(secondExpandItem));
final ExpandItem thirdExpandItem = createExpandItem("Parent");
final ExpandOption thirdExpandOption = new ExpandOptionDouble("", singletonList(thirdExpandItem));
when(secondExpandItem.getExpandOption()).thenReturn(thirdExpandOption);
when(expandItem.getExpandOption()).thenReturn(secondExpandOption);
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksTwoExpandLevelAboveMaxLevel2() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem1 = createExpandItem("Parent");
final ExpandItem expandItem2 = createExpandItem("Parent");
final ExpandOption expandOption = new ExpandOptionDouble("", Arrays.asList(expandItem2, expandItem1, expandItem2));
final ExpandItem secondExpandItem = createExpandItem("Parent");
final ExpandOption secondExpandOption = new ExpandOptionDouble("", singletonList(secondExpandItem));
final ExpandItem thirdExpandItem = createExpandItem("Parent");
final ExpandOption thirdExpandOption = new ExpandOptionDouble("", singletonList(thirdExpandItem));
when(secondExpandItem.getExpandOption()).thenReturn(thirdExpandOption);
when(expandItem1.getExpandOption()).thenReturn(secondExpandOption);
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksOneExpandWithLevelBelowMaxLevel() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem = createExpandItem("Parent");
final LevelsExpandOption levelOption = mock(LevelsExpandOption.class);
when(expandItem.getLevelsOption()).thenReturn(levelOption);
when(levelOption.getValue()).thenReturn(1);
final ExpandOption expandOption = new ExpandOptionDouble("", Collections.singletonList(expandItem));
cut = new JPAExpandWatchDog(annotatable);
assertDoesNotThrow(() -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksOneExpandWithLevelAboveMaxLevel() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem = createExpandItem("Parent");
final LevelsExpandOption levelOption = mock(LevelsExpandOption.class);
when(expandItem.getLevelsOption()).thenReturn(levelOption);
when(levelOption.getValue()).thenReturn(3);
final ExpandOption expandOption = new ExpandOptionDouble("", Collections.singletonList(expandItem));
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksTwoExpandWithLevelAboveMaxLevel() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem1 = createExpandItem("Parent");
final ExpandItem expandItem2 = createExpandItem("Child");
final LevelsExpandOption levelOption = mock(LevelsExpandOption.class);
when(expandItem1.getLevelsOption()).thenReturn(levelOption);
when(levelOption.getValue()).thenReturn(3);
final ExpandOption expandOption = new ExpandOptionDouble("", Arrays.asList(expandItem2, expandItem1, expandItem2));
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksOneExpandWithMaxLevel() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem1 = createExpandItem("Parent");
final LevelsExpandOption levelOption = mock(LevelsExpandOption.class);
when(expandItem1.getLevelsOption()).thenReturn(levelOption);
when(levelOption.getValue()).thenReturn(0);
when(levelOption.isMax()).thenReturn(Boolean.TRUE);
final ExpandOption expandOption = new ExpandOptionDouble("", Arrays.asList(expandItem1));
cut = new JPAExpandWatchDog(annotatable);
assertDoesNotThrow(() -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksTwoExpandWithOneMaxLevel() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem1 = createExpandItem("Parent");
final ExpandItem expandItem2 = createExpandItem("Child");
final LevelsExpandOption levelOption = mock(LevelsExpandOption.class);
when(expandItem1.getLevelsOption()).thenReturn(levelOption);
when(levelOption.getValue()).thenReturn(0);
when(levelOption.isMax()).thenReturn(Boolean.TRUE);
final LevelsExpandOption levelOption2 = mock(LevelsExpandOption.class);
when(expandItem2.getLevelsOption()).thenReturn(levelOption2);
when(levelOption2.getValue()).thenReturn(1);
final ExpandOption expandOption = new ExpandOptionDouble("", Arrays.asList(expandItem1, expandItem2));
cut = new JPAExpandWatchDog(annotatable);
assertDoesNotThrow(() -> cut.watch(expandOption, queryPathOnlyRoot()));
}
@Test
void testWatchChecksTwoExpandWithOneMaxLevelOneAboveMaxLevel() throws ODataJPAProcessException {
final Optional<JPAAnnotatable> annotatable = createAnnotatable(true, 2);
final ExpandItem expandItem1 = createExpandItem("Parent");
final ExpandItem expandItem2 = createExpandItem("Child");
final LevelsExpandOption levelOption = mock(LevelsExpandOption.class);
when(expandItem1.getLevelsOption()).thenReturn(levelOption);
when(levelOption.getValue()).thenReturn(0);
when(levelOption.isMax()).thenReturn(Boolean.TRUE);
final LevelsExpandOption levelOption2 = mock(LevelsExpandOption.class);
when(expandItem2.getLevelsOption()).thenReturn(levelOption2);
when(levelOption2.getValue()).thenReturn(3);
final ExpandOption expandOption = new ExpandOptionDouble("", Arrays.asList(expandItem1, expandItem2));
cut = new JPAExpandWatchDog(annotatable);
assertThrows(ODataJPAProcessException.class, () -> cut.watch(expandOption, queryPathOnlyRoot()));
}
private List<UriResource> queryPathOnlyRoot() {
final UriResource esUriResource = mock(UriResource.class);
when(esUriResource.getSegmentValue()).thenReturn(ES_EXTERNAL_NAME);
return singletonList(esUriResource);
}
private ExpandItem createExpandItem(final String... expandPaths) {
final ExpandItem expandItem = mock(ExpandItem.class);
final UriInfoResource uriInfoResource = mock(UriInfoResource.class);
when(expandItem.getResourcePath()).thenReturn(uriInfoResource);
final List<UriResource> expandResources = new ArrayList<>();
for (final String expandPath : expandPaths) {
final UriResource uriResource = mock(UriResource.class);
when(uriResource.getSegmentValue()).thenReturn(expandPath);
expandResources.add(uriResource);
}
when(uriInfoResource.getUriResourceParts()).thenReturn(expandResources);
return expandItem;
}
private static Optional<JPAAnnotatable> createAnnotatable(final Boolean isExpandable, final Integer levels,
final String... nonExpandable) {
final JPAAnnotatable annotatable = mock(JPAAnnotatable.class);
final CsdlAnnotation annotation = mock(CsdlAnnotation.class);
final CsdlDynamicExpression expression = mock(CsdlDynamicExpression.class);
final CsdlRecord record = mock(CsdlRecord.class);
final CsdlPropertyValue expandableValue = createConstantsExpression(JPAExpandWatchDog.EXPANDABLE,
isExpandable == null ? null : isExpandable.toString());
final CsdlPropertyValue levelsValue = createConstantsExpression(JPAExpandWatchDog.MAX_LEVELS,
levels == null ? null : levels.toString());
final CsdlPropertyValue nonExpandableValue = createCollectionExpression(JPAExpandWatchDog.NON_EXPANDABLE_PROPERTIES,
asExpression(nonExpandable));
final List<CsdlPropertyValue> propertyValues = Arrays.asList(expandableValue, levelsValue, nonExpandableValue);
when(annotation.getExpression()).thenReturn(expression);
when(expression.asDynamic()).thenReturn(expression);
when(expression.asRecord()).thenReturn(record);
when(record.getPropertyValues()).thenReturn(propertyValues);
when(annotatable.getExternalName()).thenReturn(ES_EXTERNAL_NAME);
try {
when(annotatable.getAnnotation(JPAExpandWatchDog.VOCABULARY_ALIAS, JPAExpandWatchDog.TERM))
.thenReturn(annotation);
} catch (final ODataJPAModelException e) {
fail();
}
return Optional.of(annotatable);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAJavaFunctionProcessorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAJavaFunctionProcessorTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.EntityManager;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmEnumType;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmParameter;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPAODataQueryContext;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEnumerationAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJavaFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPADBAdaptorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.testobjects.FileAccess;
import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionActionConstructor;
import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionForFilter;
import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionParameter;
class JPAJavaFunctionProcessorTest {
private JPAJavaFunctionProcessor cut;
private JPAODataQueryContext queryContext;
private UriResourceFunction uriResourceFunction;
private JPAJavaFunction jpaFunction;
private EdmFunction edmFunction;
private JPAServiceDocument sd;
private List<UriParameter> uriParameters;
private EntityManager em;
private JPAHttpHeaderMap header;
private JPARequestParameterMap requestParameter;
@BeforeEach
void setup() {
uriParameters = new ArrayList<>();
sd = mock(JPAServiceDocument.class);
jpaFunction = mock(JPAJavaFunction.class);
uriResourceFunction = mock(UriResourceFunction.class);
queryContext = mock(JPAODataQueryContext.class);
em = mock(EntityManager.class);
header = mock(JPAHttpHeaderMap.class);
requestParameter = mock(JPARequestParameterMap.class);
edmFunction = mock(EdmFunction.class);
when(uriResourceFunction.getFunction()).thenReturn(edmFunction);
}
@Test
void testConstructorQueryContextParameter() throws NoSuchMethodException, SecurityException, ODataJPAModelException,
EdmPrimitiveTypeException {
final Constructor<TestFunctionForFilter> c = TestFunctionForFilter.class.getConstructor(JPAODataQueryContext.class);
final Method m = TestFunctionForFilter.class.getMethod("at2", LocalDate.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("date", m);
setPrimitiveValue(LocalDate.now(), parameter);
doReturn(c).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("date")).thenReturn(parameter.getMiddle());
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, queryContext);
assertDoesNotThrow(() -> cut.process());
}
@Test
void testConstructorWithThreeParameter() throws ODataApplicationException, NoSuchMethodException, SecurityException,
ODataJPAModelException, EdmPrimitiveTypeException {
final Constructor<TestFunctionActionConstructor> constructor = TestFunctionActionConstructor.class.getConstructor(
EntityManager.class, JPAHttpHeaderMap.class, JPARequestParameterMap.class);
final Method method = TestFunctionActionConstructor.class.getMethod("func", LocalDate.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("date", method);
setPrimitiveValue(LocalDate.now(), parameter);
doReturn(constructor).when(jpaFunction).getConstructor();
doReturn(method).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("date")).thenReturn(parameter.getMiddle());
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, em, header, requestParameter,
queryContext);
assertTrue((Boolean) cut.process());
}
@Test
void testParameterNull() throws ODataApplicationException, NoSuchMethodException, SecurityException,
ODataJPAModelException, EdmPrimitiveTypeException {
final Constructor<TestFunctionActionConstructor> c = TestFunctionActionConstructor.class.getConstructor(
EntityManager.class, JPAHttpHeaderMap.class, JPARequestParameterMap.class);
final Method m = TestFunctionActionConstructor.class.getMethod("func", LocalDate.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("date", m);
setPrimitiveValue(null, parameter);
doReturn(c).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("date")).thenReturn(parameter.getMiddle());
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, em, header, requestParameter,
queryContext);
assertTrue((Boolean) cut.process());
}
@Test
void testParameterEnum() throws ODataApplicationException, NoSuchMethodException, SecurityException,
ODataJPAModelException {
final Constructor<TestFunctionActionConstructor> c = TestFunctionActionConstructor.class.getConstructor(
EntityManager.class, JPAHttpHeaderMap.class, JPARequestParameterMap.class);
final Method m = TestFunctionActionConstructor.class.getMethod("funcEnum", FileAccess.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("access", m);
setEnumValue(FileAccess.Write, parameter, true);
doReturn(c).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("access")).thenReturn(parameter.getMiddle());
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, em, header, requestParameter,
queryContext);
assertTrue((Boolean) cut.process());
}
@Test
void testThrowsExceptionEnumNotFound() throws NoSuchMethodException, SecurityException, ODataJPAModelException {
final Constructor<TestFunctionActionConstructor> c = TestFunctionActionConstructor.class.getConstructor(
EntityManager.class, JPAHttpHeaderMap.class, JPARequestParameterMap.class);
final Method m = TestFunctionActionConstructor.class.getMethod("funcEnum", FileAccess.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("access", m);
setEnumValue(FileAccess.Write, parameter, false);
doReturn(c).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("access")).thenReturn(parameter.getMiddle());
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, em, header, requestParameter,
queryContext);
assertThrows(ODataJPAProcessorException.class, () -> cut.process());
}
@Test
void testThrowsExceptionOnUnsupportedType() throws NoSuchMethodException, SecurityException, ODataJPAModelException {
final Constructor<TestFunctionActionConstructor> c = TestFunctionActionConstructor.class.getConstructor(
EntityManager.class, JPAHttpHeaderMap.class, JPARequestParameterMap.class);
final Method m = TestFunctionActionConstructor.class.getMethod("funcEnum", FileAccess.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("access", m);
setComplexValue(m, parameter);
doReturn(c).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("access")).thenReturn(parameter.getMiddle());
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, em, header, requestParameter,
queryContext);
assertThrows(ODataJPADBAdaptorException.class, () -> cut.process());
}
@Test
void testRethrowsExceptionOnInvocationError() throws NoSuchMethodException, SecurityException, ODataJPAModelException,
EdmPrimitiveTypeException {
final Constructor<TestFunctionForFilter> c = TestFunctionForFilter.class.getConstructor(JPAODataQueryContext.class);
final Method m = TestFunctionForFilter.class.getMethod("at2", LocalDate.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("date", m);
setPrimitiveValue("at2", parameter);
doReturn(c).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("date")).thenReturn(parameter.getMiddle());
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, queryContext);
assertThrows(ODataJPAProcessorException.class, () -> cut.process());
}
@Test
void testRethrowsExceptionOnInvocationTargetError() throws NoSuchMethodException, SecurityException,
ODataJPAModelException, EdmPrimitiveTypeException {
final Constructor<TestFunctionParameter> c = TestFunctionParameter.class.getConstructor(EntityManager.class);
final Method m = TestFunctionParameter.class.getMethod("sumThrowsException", Integer.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("A", m);
setPrimitiveValue(Integer.valueOf(5), parameter);
doReturn(c).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("A")).thenReturn(parameter.getMiddle());
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, queryContext);
assertThrows(ODataApplicationException.class, () -> cut.process());
}
@Test
void testRethrowsExceptionOnParameterError() throws NoSuchMethodException, SecurityException, ODataJPAModelException,
EdmPrimitiveTypeException {
final Constructor<TestFunctionForFilter> c = TestFunctionForFilter.class.getConstructor(JPAODataQueryContext.class);
final Method m = TestFunctionForFilter.class.getMethod("at2", LocalDate.class);
final Triple<UriParameter, EdmParameter, JPAParameter> parameter = createParameter("date", m);
setPrimitiveValue(LocalDate.now(), parameter);
doReturn(c).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriResourceFunction.getParameters()).thenReturn(uriParameters);
when(edmFunction.getParameter("date")).thenReturn(parameter.getMiddle());
when(((EdmPrimitiveType) parameter.getMiddle().getType())
.valueOfString(any(), any(), any(), any(), any(), any(), any()))
.thenThrow(EdmPrimitiveTypeException.class);
cut = new JPAJavaFunctionProcessor(sd, uriResourceFunction, jpaFunction, queryContext);
assertThrows(ODataJPADBAdaptorException.class, () -> cut.process());
}
private Triple<UriParameter, EdmParameter, JPAParameter> createParameter(final String name, final Method m)
throws ODataJPAModelException {
final UriParameter uriParameter = mock(UriParameter.class);
when(uriParameter.getName()).thenReturn(name);
uriParameters.add(uriParameter);
final JPAParameter parameter = mock(JPAParameter.class);
when(parameter.getName()).thenReturn(name);
doReturn(Short.class).when(parameter).getType();
when(jpaFunction.getParameter(m.getParameters()[0])).thenReturn(parameter);
final EdmParameter edmParameter = mock(EdmParameter.class);
return new ImmutableTriple<>(uriParameter, edmParameter, parameter);
}
private void setPrimitiveValue(final Object value, final Triple<UriParameter, EdmParameter, JPAParameter> parameter)
throws EdmPrimitiveTypeException {
when(parameter.getLeft().getText()).thenReturn(value == null ? null : value.toString());
final EdmPrimitiveType edmType = mock(EdmPrimitiveType.class);
when(parameter.getMiddle().getType()).thenReturn(edmType);
when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE);
when(edmType.valueOfString(any(), any(), any(), any(), any(), any(), any())).thenReturn(value);
}
private void setEnumValue(final Object value, final Triple<UriParameter, EdmParameter, JPAParameter> parameter,
final boolean enumFound) throws ODataJPAModelException {
final String ENUM_FQN = "test.FileAccess";
final FullQualifiedName fqn = new FullQualifiedName(ENUM_FQN);
final JPAEnumerationAttribute enumAttribute = mock(JPAEnumerationAttribute.class);
when(parameter.getLeft().getText()).thenReturn(value == null ? null : value.toString());
final EdmEnumType edmType = mock(EdmEnumType.class);
when(parameter.getMiddle().getType()).thenReturn(edmType);
when(parameter.getRight().getTypeFQN()).thenReturn(fqn);
when(edmType.getKind()).thenReturn(EdmTypeKind.ENUM);
if (enumFound)
when(sd.getEnumType(ENUM_FQN)).thenReturn(enumAttribute);
else
when(sd.getEnumType(ENUM_FQN)).thenReturn(null);
when(enumAttribute.enumOf(value.toString())).thenReturn(value);
}
private void setComplexValue(final Object value, final Triple<UriParameter, EdmParameter, JPAParameter> parameter) {
when(parameter.getLeft().getText()).thenReturn(value == null ? null : value.toString());
final EdmComplexType edmType = mock(EdmComplexType.class);
when(parameter.getMiddle().getType()).thenReturn(edmType);
when(edmType.getKind()).thenReturn(EdmTypeKind.COMPLEX);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
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.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey;
import com.sap.olingo.jpa.processor.core.testmodel.InhouseAddress;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
class TestJPAUpdateProcessor extends TestJPAModifyProcessor {
@Test
void testHookIsCalled() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertTrue(spy.called);
}
@Test
void testHttpMethodProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
when(request.getMethod()).thenReturn(HttpMethod.PATCH);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpMethod.PATCH, spy.method);
}
@Test
void testEntityTypeProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
when(request.getMethod()).thenReturn(HttpMethod.PATCH);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertTrue(spy.et instanceof JPAEntityType);
}
@SuppressWarnings("unchecked")
@Test
void testJPAAttributes() throws ODataException, UnsupportedEncodingException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
when(request.getMethod()).thenReturn(HttpMethod.PATCH);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
final InputStream is = new ByteArrayInputStream("{\"ID\" : \"35\", \"Country\" : \"USA\"}".getBytes("UTF-8"));
when(request.getBody()).thenReturn(is);
final Map<String, Object> jpaAttributes = new HashMap<>();
jpaAttributes.put("id", "35");
jpaAttributes.put("country", "USA");
when(convHelper.convertProperties(any(OData.class), any(JPAStructuredType.class), any(List.class)))
.thenReturn(jpaAttributes);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(2, spy.jpaAttributes.size());
}
@SuppressWarnings("unchecked")
@Test
void testProvideSimplePrimitivePutAsPatch() throws ODataException, UnsupportedEncodingException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final EdmProperty odataProperty = mock(EdmProperty.class);
final UriResourceProperty uriProperty = mock(UriResourceProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(odataProperty);
when(odataProperty.getName()).thenReturn("StreetName");
when(request.getMethod()).thenReturn(HttpMethod.PUT);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
final InputStream is = new ByteArrayInputStream("{ \"value\": \"New Road\"}".getBytes("UTF-8"));
when(request.getBody()).thenReturn(is);
final Map<String, Object> jpaAttributes = new HashMap<>();
jpaAttributes.put("streetName", "New Road");
when(convHelper.convertProperties(any(OData.class), any(JPAStructuredType.class), any(List.class)))
.thenReturn(jpaAttributes);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(1, spy.jpaAttributes.size());
assertEquals(HttpMethod.PATCH, spy.method);
}
@Disabled("Not implemented yet")
@Test
void testProvideSimpleComplexPutAsPatch() {
fail();
}
@SuppressWarnings("unchecked")
@Test
void testProvidePrimitiveCollectionPutAsPatch() throws ODataException, UnsupportedEncodingException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final EdmProperty odataProperty = mock(EdmProperty.class);
final UriResourceProperty uriProperty = mock(UriResourceProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(odataProperty);
when(odataProperty.getName()).thenReturn("Comments");
when(odataProperty.isCollection()).thenReturn(true);
when(request.getMethod()).thenReturn(HttpMethod.PUT);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
final InputStream is = new ByteArrayInputStream("{ \"value\": \"[\"YAC\",\"WTN\"]\"}".getBytes("UTF-8"));
when(request.getBody()).thenReturn(is);
final Map<String, Object> jpaAttributes = new HashMap<>();
final List<String> lines = new ArrayList<>(2);
lines.add("YAC");
lines.add("WTN");
jpaAttributes.put("comment", lines);
when(convHelper.convertProperties(any(OData.class), any(JPAStructuredType.class), any(List.class)))
.thenReturn(jpaAttributes);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(1, spy.jpaAttributes.size());
assertEquals(HttpMethod.PATCH, spy.method);
}
@SuppressWarnings("unchecked")
@Test
void testProvideComplexCollectionPutAsPatch() throws ODataException, UnsupportedEncodingException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final EdmProperty odataProperty = mock(EdmProperty.class);
final UriResourceProperty uriProperty = mock(UriResourceProperty.class);
pathParts.add(uriProperty);
when(uriProperty.getProperty()).thenReturn(odataProperty);
when(odataProperty.getName()).thenReturn("InhouseAddress");
when(odataProperty.isCollection()).thenReturn(true);
when(request.getMethod()).thenReturn(HttpMethod.PUT);
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
final InputStream is = new ByteArrayInputStream(
"{ \"value\": \"[{\"RoomNumber\": 25,\"Floor\": 2,\"TaskID\": \"DEV\",\"Building\": \"2\"}]\"}"
.getBytes("UTF-8"));
when(request.getBody()).thenReturn(is);
final Map<String, Object> jpaAttributes = new HashMap<>();
final List<InhouseAddress> lines = new ArrayList<>(2);
lines.add(new InhouseAddress("DEV", "2"));
jpaAttributes.put("inhouseAddress", lines);
when(convHelper.convertProperties(any(OData.class), any(JPAStructuredType.class), any(List.class)))
.thenReturn(jpaAttributes);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(1, spy.jpaAttributes.size());
assertEquals(HttpMethod.PATCH, spy.method);
}
@Test
void testHeadersProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final Map<String, List<String>> headers = new HashMap<>();
when(request.getAllHeaders()).thenReturn(headers);
headers.put("If-Match", Arrays.asList("2"));
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.headers);
assertEquals(1, spy.headers.size());
assertNotNull(spy.headers.get("If-Match"));
assertEquals("2", spy.headers.get("If-Match").get(0));
}
@Test
void testClaimsProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
final JPAODataClaimProvider provider = new JPAODataClaimsProvider();
final Optional<JPAODataClaimProvider> claims = Optional.of(provider);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(requestContext.getClaimsProvider()).thenReturn(claims);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.claims);
assertTrue(spy.claims.isPresent());
assertEquals(provider, spy.claims.get());
}
@Test
void testGroupsProvided() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
final JPAODataGroupsProvider provider = new JPAODataGroupsProvider();
provider.addGroup("Person");
final Optional<JPAODataGroupProvider> groups = Optional.of(provider);
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(requestContext.getGroupsProvider()).thenReturn(groups);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(spy.groups);
assertFalse(spy.groups.isEmpty());
assertEquals("Person", spy.groups.get(0));
}
@Test
void testMinimalResponseUpdateStatusCode() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
when(request.getMethod()).thenReturn(HttpMethod.PATCH);
final RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(false, new Organization()));
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode());
}
@Test
void testMinimalResponseCreatedStatusCode() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
when(request.getMethod()).thenReturn(HttpMethod.PATCH);
final RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(true, new Organization()));
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode());
}
@Test
void testMinimalResponseUpdatePreferHeader() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
when(request.getMethod()).thenReturn(HttpMethod.PATCH);
final RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(false, new Organization()));
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(PREFERENCE_APPLIED, response.getHeader(HttpHeader.PREFERENCE_APPLIED));
}
@Test
void testMinimalResponseCreatedPreferHeader() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
when(request.getMethod()).thenReturn(HttpMethod.PATCH);
final RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(true, new Organization()));
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(PREFERENCE_APPLIED, response.getHeader(HttpHeader.PREFERENCE_APPLIED));
}
@Test
void testRepresentationResponseUpdatedStatusCode() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(false,
new Organization())));
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());
}
@Test
void testRepresentationResponseCreatedStatusCode() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(true,
new Organization())));
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode());
}
@Test
void testRepresentationResponseUpdatedErrorMissingEntity() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(false, null)));
try {
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
} catch (final ODataJPAProcessException e) {
assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode());
return;
}
fail();
}
@Test
void testRepresentationResponseCreatedErrorMissingEntity() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(true, null)));
try {
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
} catch (final ODataJPAProcessException e) {
assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode());
return;
}
fail();
}
@Test
void testRepresentationResponseUpdatedWithKey() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(false,
new Organization())));
final Map<String, Object> keys = new HashMap<>();
keys.put("iD", "35");
when(convHelper.convertUriKeys(any(), any(), any())).thenReturn(keys);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());
}
@Test
void testCallsValidateChangesOnSuccessfulProcessing() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(1, spy.noValidateCalls);
}
@Test
void testDoesNotCallsValidateChangesOnForeignTransaction() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
when(factory.hasActiveTransaction()).thenReturn(Boolean.TRUE);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertEquals(0, spy.noValidateCalls);
}
@Test
void testDoesNotCallsValidateChangesOnError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
when(request.getMethod()).thenReturn(HttpMethod.PATCH);
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).updateEntity(any(JPARequestEntity.class), any(EntityManager.class),
any(HttpMethod.class));
try {
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
} catch (final ODataApplicationException e) {
verify(handler, never()).validateChanges(em);
return;
}
fail();
}
@Test
void testDoesRollbackIfValidateRaisesError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em);
assertThrows(ODataApplicationException.class,
() -> processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testDoesRollbackIfUpdateRaisesError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.BAD_REQUEST)).when(handler).updateEntity(any(), any(), any());
assertThrows(ODataApplicationException.class,
() -> processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testDoesRollbackIfUpdateRaisesArbitraryError() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
doThrow(new RuntimeException("Test")).when(handler).updateEntity(any(), any(), any());
assertThrows(ODataException.class,
() -> processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testDoesRollbackOnEmptyResponse() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
when(handler.updateEntity(any(), any(), any())).thenReturn(null);
assertThrows(ODataException.class,
() -> processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testDoesRollbackOnWrongResponse() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final JPAUpdateResult result = new JPAUpdateResult(false, "");
final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class);
when(requestContext.getCUDRequestHandler()).thenReturn(handler);
when(handler.updateEntity(any(), any(), any())).thenReturn(result);
assertThrows(ODataException.class,
() -> processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON));
verify(transaction, never()).commit();
verify(transaction, times(1)).rollback();
}
@Test
void testResponseErrorIfNull() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(null));
try {
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
} catch (final ODataJPAProcessException e) {
assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode());
return;
}
fail();
}
@Test
void testResponseUpdateLink() throws ODataException {
final AdministrativeDivisionKey key = new AdministrativeDivisionKey("Eurostat", "NUTS2", "DE60");
final AdministrativeDivision resultEntity = new AdministrativeDivision(key);
final AdministrativeDivisionKey childKey = new AdministrativeDivisionKey("Eurostat", "NUTS3", "DE600");
final AdministrativeDivision childEntity = new AdministrativeDivision(childKey);
childEntity.setParentCodeID("NUTS2");
childEntity.setParentDivisionCode("DE600");
final JPAUpdateResult result = new JPAUpdateResult(false, resultEntity);
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareLinkRequest(new RequestHandleSpy(result));
resultEntity.setChildren(new ArrayList<>(Arrays.asList(childEntity)));
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
assertNotNull(response);
}
@Test
void testOwnTransactionCommitted() throws ODataException {
final ODataResponse response = new ODataResponse();
final ODataRequest request = prepareSimpleRequest();
final RequestHandleSpy spy = new RequestHandleSpy();
when(requestContext.getCUDRequestHandler()).thenReturn(spy);
processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON);
verify(transaction, times(1)).commit();
}
class RequestHandleSpy extends JPAAbstractCUDRequestHandler {
public int noValidateCalls;
public JPAEntityType et;
public Map<String, Object> jpaAttributes;
public EntityManager em;
public boolean called = false;
public HttpMethod method;
public Map<String, List<String>> headers;
private final JPAUpdateResult change;
public Optional<JPAODataClaimProvider> claims;
public List<String> groups;
RequestHandleSpy() {
this(new JPAUpdateResult(true, new Organization()));
}
RequestHandleSpy(final JPAUpdateResult typeOfChange) {
this.change = typeOfChange;
}
@Override
public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em,
final HttpMethod verb) throws ODataJPAProcessException {
this.et = requestEntity.getEntityType();
this.jpaAttributes = requestEntity.getData();
this.em = em;
this.called = true;
this.method = verb;
this.headers = requestEntity.getAllHeader();
this.claims = requestEntity.getClaims();
this.groups = requestEntity.getGroups();
return change;
}
@Override
public void validateChanges(final EntityManager em) throws ODataJPAProcessException {
this.noValidateCalls++;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAInstanceCreatorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAInstanceCreatorTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriParameter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.testobjects.ClassWithIdClassConstructor;
import com.sap.olingo.jpa.processor.core.testobjects.ClassWithIdClassWithoutConstructor;
import com.sap.olingo.jpa.processor.core.testobjects.ClassWithMultipleKeysConstructor;
import com.sap.olingo.jpa.processor.core.testobjects.ClassWithMultipleKeysNoConstructor;
import com.sap.olingo.jpa.processor.core.testobjects.ClassWithMultipleKeysSetter;
import com.sap.olingo.jpa.processor.core.testobjects.ClassWithOneKeyAndEmptyConstructor;
import com.sap.olingo.jpa.processor.core.testobjects.ClassWithOneKeyConstructor;
class JPAInstanceCreatorTest {
private JPAInstanceCreator<?> cut;
private OData odata;
private JPAEntityType et;
@BeforeEach
void setup() {
odata = OData.newInstance();
et = mock(JPAEntityType.class);
}
@Test
void testGetConstructorWithIdClass() throws ODataJPAModelException, ODataJPAProcessorException {
fillCompoundKey();
buildTypeWithCompoundKey(ClassWithIdClassConstructor.class);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Constructor<Object>> constructor = cut.determinePreferredConstructor();
assertTrue(constructor.isPresent());
assertEquals(1, constructor.get().getParameterCount());
}
@Test
void testGetConstructorWithCompoundKey() throws ODataJPAModelException, ODataJPAProcessorException {
fillCompoundKey();
buildTypeWithCompoundKey(ClassWithMultipleKeysSetter.class);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Constructor<Object>> constructor = cut.determinePreferredConstructor();
assertTrue(constructor.isPresent());
assertEquals(0, constructor.get().getParameterCount());
}
@Test
void testGetConstructorNoSetterReturnsNull() throws ODataJPAModelException, ODataJPAProcessorException {
fillCompoundKey();
buildTypeWithCompoundKey(ClassWithMultipleKeysConstructor.class);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Constructor<Object>> constructor = cut.determinePreferredConstructor();
assertFalse(constructor.isPresent());
}
@Test
void testGetConstructorSingleKey() throws ODataJPAModelException, ODataJPAProcessorException {
final JPAAttribute key = mock(JPAAttribute.class);
final List<JPAAttribute> keys = Arrays.asList(key);
when(key.getInternalName()).thenReturn("key");
when(key.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return String.class;
}
});
when(et.getKey()).thenReturn(keys);
when(et.getTypeClass()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ClassWithOneKeyConstructor.class;
}
});
when(et.getKeyType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return UUID.class;
}
});
when(et.hasCompoundKey()).thenReturn(false);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Constructor<Object>> constructor = cut.determinePreferredConstructor();
assertTrue(constructor.isPresent());
assertEquals(1, constructor.get().getParameterCount());
assertEquals(UUID.class, constructor.get().getParameterTypes()[0]);
}
@Test
void testGetConstructorSingleKeyNoKey() throws ODataJPAModelException, ODataJPAProcessorException {
final List<JPAAttribute> keys = Arrays.asList(fillOneKey("key", UUID.class, EdmPrimitiveTypeKind.Guid));
buildTypeWithSingleKey(keys);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Constructor<Object>> constructor = cut.determinePreferredConstructor();
assertTrue(constructor.isPresent());
assertEquals(1, constructor.get().getParameterCount());
assertEquals(UUID.class, constructor.get().getParameterTypes()[0]);
}
@Test
void testGetConstructorNoResult() throws ODataJPAModelException, ODataJPAProcessorException {
fillCompoundKey();
when(et.getTypeClass()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ClassWithMultipleKeysNoConstructor.class;
}
});
when(et.getKeyType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ClassWithMultipleKeysNoConstructor.class;
}
});
when(et.hasCompoundKey()).thenReturn(true);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Constructor<Object>> constructor = cut.determinePreferredConstructor();
assertFalse(constructor.isPresent());
}
@Test
void testGetConstructorRethrowsException() throws ODataJPAModelException {
when(et.getKey()).thenThrow(ODataJPAModelException.class);
when(et.getTypeClass()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ClassWithOneKeyAndEmptyConstructor.class;
}
});
when(et.getKeyType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return UUID.class;
}
});
when(et.hasCompoundKey()).thenReturn(false);
cut = new JPAInstanceCreator<>(odata, et);
assertThrows(ODataJPAProcessorException.class, () -> cut.determinePreferredConstructor());
}
@Test
void testCreateInstanceWithIdClass() throws ODataJPAProcessorException, ODataJPAModelException {
fillCompoundKey();
buildTypeWithCompoundKey(ClassWithIdClassConstructor.class);
final UriParameter keyParam1 = fillUriParameter("id1", "'Test'");
final UriParameter keyParam2 = fillUriParameter("id2", "12");
final UriParameter keyParam3 = fillUriParameter("id3", "'654645'");
final List<UriParameter> keyPredicates = Arrays.asList(keyParam1, keyParam2, keyParam3);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Object> instance = cut.createInstance(keyPredicates);
assertNotNull(instance);
assertTrue(instance.isPresent());
final ClassWithIdClassConstructor act = (ClassWithIdClassConstructor) instance.get();
assertEquals("Test", act.getKey().getId1());
assertEquals(12, act.getKey().getId2());
assertEquals("654645", act.getKey().getId3());
}
@Test
void testCreateInstanceWithCompoundKeySetter() throws ODataJPAProcessorException, ODataJPAModelException {
fillCompoundKey();
buildTypeWithCompoundKey(ClassWithMultipleKeysSetter.class);
final UriParameter keyParam1 = fillUriParameter("id1", "'Test'");
final UriParameter keyParam2 = fillUriParameter("id2", "12");
final UriParameter keyParam3 = fillUriParameter("id3", "'654645'");
final List<UriParameter> keyPredicates = Arrays.asList(keyParam1, keyParam2, keyParam3);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Object> instance = cut.createInstance(keyPredicates);
assertNotNull(instance);
assertTrue(instance.isPresent());
final ClassWithMultipleKeysSetter act = (ClassWithMultipleKeysSetter) instance.get();
assertEquals("Test", act.getId1());
assertEquals(12, act.getId2());
assertEquals("654645", act.getId3());
}
@Test
void testCreateInstanceWithSingleKey() throws ODataJPAProcessorException, ODataJPAModelException {
final List<JPAAttribute> keys = Arrays.asList(fillOneKey("key", UUID.class, EdmPrimitiveTypeKind.Guid));
buildTypeWithSingleKey(keys);
final UUID value = UUID.randomUUID();
final UriParameter keyParam1 = fillUriParameter("key", value.toString());
final List<UriParameter> keyPredicates = Arrays.asList(keyParam1);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Object> instance = cut.createInstance(keyPredicates);
assertNotNull(instance);
assertTrue(instance.isPresent());
final ClassWithOneKeyAndEmptyConstructor act = (ClassWithOneKeyAndEmptyConstructor) instance.get();
assertEquals(value, act.getKey());
}
@Test
void testCreateInstanceReturnsEmptyIfNoConstructorFound() throws ODataJPAModelException, ODataJPAProcessorException {
fillCompoundKey();
final UriParameter keyParam1 = fillUriParameter("id1", "'Test'");
final UriParameter keyParam2 = fillUriParameter("id2", "12");
final UriParameter keyParam3 = fillUriParameter("id3", "'654645'");
final List<UriParameter> keyPredicates = Arrays.asList(keyParam1, keyParam2, keyParam3);
when(et.getTypeClass()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ClassWithMultipleKeysNoConstructor.class;
}
});
when(et.getKeyType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ClassWithMultipleKeysNoConstructor.class;
}
});
when(et.hasCompoundKey()).thenReturn(true);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Object> constructor = cut.createInstance(keyPredicates);
assertFalse(constructor.isPresent());
}
@Test
void testCreateInstanceRethrowsException() throws ODataJPAModelException {
final List<JPAAttribute> keys = Arrays.asList(fillOneKey("key", UUID.class, EdmPrimitiveTypeKind.Guid));
buildTypeWithSingleKey(keys);
final UUID value = UUID.randomUUID();
final UriParameter keyParam1 = fillUriParameter("key", value.toString());
final List<UriParameter> keyPredicates = Arrays.asList(keyParam1);
when(et.getPath("key")).thenThrow(ODataJPAModelException.class);
cut = new JPAInstanceCreator<>(odata, et);
assertThrows(ODataJPAProcessorException.class, () -> cut.createInstance(keyPredicates));
}
@Test
void testCreateInstanceReturnsEmptyIdClassNoConstructor() throws ODataJPAProcessorException, ODataJPAModelException {
fillCompoundKey();
buildTypeWithCompoundKey(ClassWithIdClassWithoutConstructor.class, ClassWithMultipleKeysConstructor.class);
final UriParameter keyParam1 = fillUriParameter("id1", "'Test'");
final UriParameter keyParam2 = fillUriParameter("id2", "12");
final UriParameter keyParam3 = fillUriParameter("id3", "'654645'");
final List<UriParameter> keyPredicates = Arrays.asList(keyParam1, keyParam2, keyParam3);
cut = new JPAInstanceCreator<>(odata, et);
final Optional<Object> instance = cut.createInstance(keyPredicates);
assertNotNull(instance);
assertFalse(instance.isPresent());
}
private UriParameter fillUriParameter(final String name, final String value) {
final UriParameter keyParam1 = mock(UriParameter.class);
when(keyParam1.getName()).thenReturn(name);
when(keyParam1.getText()).thenReturn(value);
return keyParam1;
}
private void buildTypeWithCompoundKey(final Class<?> typeClazz) {
buildTypeWithCompoundKey(typeClazz, ClassWithMultipleKeysSetter.class);
}
private void buildTypeWithCompoundKey(final Class<?> typeClazz, final Class<?> idClass) {
when(et.getTypeClass()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return typeClazz;
}
});
when(et.getKeyType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return idClass;
}
});
when(et.hasCompoundKey()).thenReturn(true);
}
private void fillCompoundKey() throws ODataJPAModelException {
final JPAAttribute id1 = fillOneKey("id1", String.class, EdmPrimitiveTypeKind.String);
final JPAAttribute id2 = fillOneKey("id2", Integer.class, EdmPrimitiveTypeKind.Int32);
final JPAAttribute id3 = fillOneKey("id3", String.class, EdmPrimitiveTypeKind.String);
final List<JPAAttribute> keys = Arrays.asList(id1, id2, id3);
when(et.getKey()).thenReturn(keys);
}
private JPAAttribute fillOneKey(final String name, final Class<?> type, final EdmPrimitiveTypeKind edmType)
throws ODataJPAModelException {
final JPAAttribute id1 = mock(JPAAttribute.class);
final JPAPath id1Path = mock(JPAPath.class);
final CsdlProperty id1Property = mock(CsdlProperty.class);
when(id1.getInternalName()).thenReturn(name);
when(id1.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return type;
}
});
when(id1.getType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return type;
}
});
when(id1.getEdmType()).thenReturn(edmType);
when(et.getPath(name)).thenReturn(id1Path);
when(et.getAttribute(name)).thenReturn(Optional.of(id1));
when(id1Path.getLeaf()).thenReturn(id1);
when(id1Property.isNullable()).thenReturn(Boolean.FALSE);
when(id1Property.getPrecision()).thenReturn(null);
when(id1Property.getScale()).thenReturn(null);
if (type == String.class)
when(id1Property.getMaxLength()).thenReturn(255);
when(id1.getProperty()).thenReturn(id1Property);
return id1;
}
private void buildTypeWithSingleKey(final List<JPAAttribute> keys) throws ODataJPAModelException {
when(et.getKey()).thenReturn(keys);
when(et.getTypeClass()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ClassWithOneKeyAndEmptyConstructor.class;
}
});
when(et.getKeyType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return UUID.class;
}
});
when(et.hasCompoundKey()).thenReturn(false);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAHookFactoryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAHookFactoryTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static java.util.Objects.requireNonNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmQueryExtensionProvider;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmTransientPropertyCalculator;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAQueryExtension;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.errormodel.DummyPropertyCalculator;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.testmodel.CurrentUserQueryExtension;
import com.sap.olingo.jpa.processor.core.testmodel.FullNameCalculator;
import com.sap.olingo.jpa.processor.core.testobjects.HeaderParamTransientPropertyConverter;
import com.sap.olingo.jpa.processor.core.testobjects.ThreeParameterTransientPropertyConverter;
import com.sap.olingo.jpa.processor.core.testobjects.TwoParameterTransientPropertyConverter;
class JPAHookFactoryTest {
private JPAHookFactory cut;
private EntityManager em;
private JPAHttpHeaderMap header;
private JPARequestParameterMap parameter;
@BeforeEach
void setup() {
em = mock(EntityManager.class);
header = new JPAHttpHeaderHashMap();
parameter = new JPARequestParameterHashMap();
cut = new JPAHookFactory(em, header, parameter);
}
@Test
void testGetCalculatorReturnsEmptyOptionalIfNotTransient() throws ODataJPAProcessorException {
final JPAAttribute attribute = mock(JPAAttribute.class);
when(attribute.isTransient()).thenReturn(false);
assertFalse(cut.getTransientPropertyCalculator(attribute).isPresent());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceNoParameter() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> c = FullNameCalculator.class.getConstructor();
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) c);
assertTrue(cut.getTransientPropertyCalculator(attribute).isPresent());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceFromCache() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> c = FullNameCalculator.class.getConstructor();
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) c);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getTransientPropertyCalculator(attribute);
assertEquals(act.get(), cut.getTransientPropertyCalculator(attribute).get());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceEntityManager() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> c = DummyPropertyCalculator.class.getConstructor(EntityManager.class);
cut = new JPAHookFactory(mock(EntityManager.class), header, parameter);
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) c);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getTransientPropertyCalculator(attribute);
assertTrue(act.isPresent());
assertNotNull(((DummyPropertyCalculator) act.get()).getEntityManager());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceHeader() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> c = HeaderParamTransientPropertyConverter.class.getConstructor(JPAHttpHeaderMap.class);
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) c);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getTransientPropertyCalculator(attribute);
assertTrue(act.isPresent());
assertNotNull(((HeaderParamTransientPropertyConverter) act.get()).getHeader());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceThreeParams() throws ODataJPAModelException, ODataJPAProcessorException,
SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> c = ThreeParameterTransientPropertyConverter.class.getConstructors()[0];
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) c);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getTransientPropertyCalculator(attribute);
assertTrue(act.isPresent());
assertNotNull(((ThreeParameterTransientPropertyConverter) act.get()).getEntityManager());
assertNotNull(((ThreeParameterTransientPropertyConverter) act.get()).getHeader());
assertNotNull(((ThreeParameterTransientPropertyConverter) act.get()).getParameter());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceTwoParameter() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> c = TwoParameterTransientPropertyConverter.class.getConstructor(EntityManager.class,
JPAHttpHeaderMap.class);
cut = new JPAHookFactory(mock(EntityManager.class), header, parameter);
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) c);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getTransientPropertyCalculator(attribute);
assertTrue(act.isPresent());
assertNotNull(((TwoParameterTransientPropertyConverter) act.get()).getEntityManager());
assertNotNull(((TwoParameterTransientPropertyConverter) act.get()).getHeader());
}
@Test
void testGetQueryExtensionReturnsEmptyOptionalIfSet() throws ODataJPAModelException,
ODataJPAProcessorException {
final JPAEntityType et = mock(JPAEntityType.class);
when(et.getQueryExtension()).thenReturn(Optional.empty());
assertFalse(cut.getQueryExtensionProvider(et).isPresent());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
void testGetQueryExtensionReturnsInstanceNoParameter() throws ODataJPAModelException, ODataJPAProcessorException,
SecurityException {
final JPAEntityType et = mock(JPAEntityType.class);
final JPAQueryExtension extension = mock(JPAQueryExtension.class);
when(et.getQueryExtension()).thenReturn(Optional.of(extension));
when(extension.getConstructor()).thenAnswer(new Answer<Constructor<? extends EdmQueryExtensionProvider>>() {
@Override
public Constructor<? extends EdmQueryExtensionProvider> answer(final InvocationOnMock invocation)
throws Throwable {
return (Constructor<? extends EdmQueryExtensionProvider>) CurrentUserQueryExtension.class
.getConstructors()[0];
}
});
assertTrue(cut.getQueryExtensionProvider(et).isPresent());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
void testGetQueryExtensionReturnsInstanceEntityManagerParameter() throws ODataJPAModelException,
ODataJPAProcessorException, SecurityException {
final JPAEntityType et = mock(JPAEntityType.class);
final JPAQueryExtension extension = mock(JPAQueryExtension.class);
when(et.getQueryExtension()).thenReturn(Optional.of(extension));
when(extension.getConstructor()).thenAnswer(new Answer<Constructor<? extends EdmQueryExtensionProvider>>() {
@Override
public Constructor<? extends EdmQueryExtensionProvider> answer(final InvocationOnMock invocation)
throws Throwable {
return (Constructor<? extends EdmQueryExtensionProvider>) ExtensionProviderWithHeaderParameter.class
.getConstructors()[0];
}
});
assertTrue(cut.getQueryExtensionProvider(et).isPresent());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
void testGetQueryExtensionReturnsInstanceAllParameter() throws ODataJPAModelException,
ODataJPAProcessorException, SecurityException {
final JPAEntityType et = mock(JPAEntityType.class);
final JPAQueryExtension extension = mock(JPAQueryExtension.class);
when(et.getQueryExtension()).thenReturn(Optional.of(extension));
when(extension.getConstructor()).thenAnswer(new Answer<Constructor<? extends EdmQueryExtensionProvider>>() {
@Override
public Constructor<? extends EdmQueryExtensionProvider> answer(final InvocationOnMock invocation)
throws Throwable {
return (Constructor<? extends EdmQueryExtensionProvider>) ExtensionProviderWithAllowedParameter.class
.getConstructors()[0];
}
});
assertTrue(cut.getQueryExtensionProvider(et).isPresent());
}
@SuppressWarnings("unused")
private static class ExtensionProviderWithAllowedParameter implements EdmQueryExtensionProvider {
private final Map<String, List<String>> header;
private final JPARequestParameterMap parameter;
@Override
public Expression<Boolean> getFilterExtension(final CriteriaBuilder cb, final From<?, ?> from) {
return null;
}
public ExtensionProviderWithAllowedParameter(final JPAHttpHeaderMap header,
final JPARequestParameterMap parameter) {
this.header = requireNonNull(header);
this.parameter = requireNonNull(parameter);
}
}
private static class ExtensionProviderWithHeaderParameter implements EdmQueryExtensionProvider {
@SuppressWarnings("unused")
private final Map<String, List<String>> header;
@Override
public Expression<Boolean> getFilterExtension(final CriteriaBuilder cb, final From<?, ?> from) {
return null;
}
@SuppressWarnings("unused")
public ExtensionProviderWithHeaderParameter(final JPAHttpHeaderMap header) {
this.header = header;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAODataRequestContextImpl.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAODataRequestContextImpl.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmTransientPropertyCalculator;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataApiVersionAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataPathInformation;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.errormodel.DummyPropertyCalculator;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
import com.sap.olingo.jpa.processor.core.testmodel.FullNameCalculator;
import com.sap.olingo.jpa.processor.core.testobjects.HeaderParamTransientPropertyConverter;
import com.sap.olingo.jpa.processor.core.testobjects.TwoParameterTransientPropertyConverter;
class TestJPAODataRequestContextImpl {
private JPAODataInternalRequestContext cut;
private JPAODataSessionContextAccess sessionContext;
private JPAODataRequestContext requestContext;
private JPAEdmProvider edmProvider;
private EntityManagerFactory emf;
private EntityManager em;
private JPAODataApiVersionAccess version;
private OData odata;
private JPAODataPathInformation pathInformation;
@BeforeEach
void setup() {
edmProvider = mock(JPAEdmProvider.class);
emf = mock(EntityManagerFactory.class);
em = mock(EntityManager.class);
sessionContext = mock(JPAODataSessionContextAccess.class);
requestContext = mock(JPAODataRequestContext.class);
pathInformation = new JPAODataPathInformation("", "", "", "");
version = mock(JPAODataApiVersionAccess.class);
odata = mock(OData.class);
when(sessionContext.getApiVersion(any())).thenReturn(version);
when(version.getEdmProvider()).thenReturn(edmProvider);
when(version.getEntityManagerFactory()).thenReturn(emf);
when(emf.createEntityManager()).thenReturn(em);
cut = new JPAODataInternalRequestContext(requestContext, sessionContext, odata);
}
@Test
void testInitialEmptyClaimsProvider() {
assertFalse(cut.getClaimsProvider().isPresent());
}
@Test
void testInitialEmptyGroupsProvider() {
assertFalse(cut.getGroupsProvider().isPresent());
}
@Test
void testReturnsSetUriInfo() throws ODataJPAIllegalAccessException {
final UriInfo exp = mock(UriInfo.class);
cut.setUriInfo(exp);
assertEquals(exp, cut.getUriInfo());
}
@Test
void testReturnsSetJPASerializer() {
final JPASerializer exp = mock(JPASerializer.class);
cut.setJPASerializer(exp);
assertEquals(exp, cut.getSerializer());
}
@Test
void testThrowsExceptionOnSetUriInfoIfUriInfoExists() throws ODataJPAIllegalAccessException {
final UriInfo uriInfo = mock(UriInfo.class);
cut.setUriInfo(uriInfo);
assertThrows(ODataJPAIllegalAccessException.class, () -> cut.setUriInfo(uriInfo));
}
@Test
void testThrowsExceptionOnUriInfoIsNull() {
assertThrows(NullPointerException.class, () -> cut.setUriInfo(null));
}
@Test
void testThrowsExceptionOnSerializerIsNull() {
assertThrows(NullPointerException.class, () -> cut.setJPASerializer(null));
}
@Test
void testCopyConstructorCopiesExternalAndAddsPageSerializer() throws ODataJPAProcessorException {
fillContextForCopyConstructor();
final UriInfo uriInfo = mock(UriInfo.class);
final JPAODataInternalRequestContext act = new JPAODataInternalRequestContext(uriInfo, cut);
assertEquals(uriInfo, act.getUriInfo());
assertCopied(act);
}
@Test
void testCopyConstructorCopiesExternalAndAddsUriInfoSerializer() throws ODataJPAProcessorException {
fillContextForCopyConstructor();
final UriInfo uriInfo = mock(UriInfo.class);
final JPASerializer serializer = mock(JPASerializer.class);
final Map<String, List<String>> header = Collections.emptyMap();
final JPAODataInternalRequestContext act = new JPAODataInternalRequestContext(uriInfo, serializer, cut, header,
pathInformation);
assertEquals(uriInfo, act.getUriInfo());
assertEquals(serializer, act.getSerializer());
assertEquals(header, act.getHeader());
assertCopied(act);
}
@Test
void testCopyConstructorCopiesExternalAndAddsUriInfoSerializerNull() throws ODataJPAProcessorException {
fillContextForCopyConstructor();
final UriInfo uriInfo = mock(UriInfo.class);
final Map<String, List<String>> header = Collections.emptyMap();
final JPAODataInternalRequestContext act = new JPAODataInternalRequestContext(uriInfo, null, cut, header,
pathInformation);
assertEquals(uriInfo, act.getUriInfo());
assertEquals(null, act.getSerializer());
assertCopied(act);
}
@Test
void testGetCalculatorReturnsEmptyOptionalIfNotTransient() throws ODataJPAProcessorException {
final JPAAttribute attribute = mock(JPAAttribute.class);
when(attribute.isTransient()).thenReturn(false);
assertFalse(cut.getCalculator(attribute).isPresent());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceNoParameter() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> constructor = FullNameCalculator.class.getConstructor();
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) constructor);
assertTrue(cut.getCalculator(attribute).isPresent());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceFromCache() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> constructor = FullNameCalculator.class.getConstructor();
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) constructor);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getCalculator(attribute);
assertEquals(act.get(), cut.getCalculator(attribute).get());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceEntityManager() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> constructor = DummyPropertyCalculator.class.getConstructor(EntityManager.class);
cut = new JPAODataInternalRequestContext(JPAODataRequestContext
.with().setEntityManager(mock(EntityManager.class)).build(), sessionContext, odata);
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) constructor);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getCalculator(attribute);
assertTrue(act.isPresent());
assertNotNull(((DummyPropertyCalculator) act.get()).getEntityManager());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceHeader() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> constructor = HeaderParamTransientPropertyConverter.class.getConstructor(
JPAHttpHeaderMap.class);
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) constructor);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getCalculator(attribute);
assertTrue(act.isPresent());
assertNotNull(((HeaderParamTransientPropertyConverter) act.get()).getHeader());
}
@SuppressWarnings("unchecked")
@Test
void testGetCalculatorReturnsInstanceTwoParameter() throws ODataJPAModelException, ODataJPAProcessorException,
NoSuchMethodException, SecurityException {
final JPAAttribute attribute = mock(JPAAttribute.class);
final Constructor<?> constructor = TwoParameterTransientPropertyConverter.class.getConstructor(EntityManager.class,
JPAHttpHeaderMap.class);
cut = new JPAODataInternalRequestContext(JPAODataRequestContext
.with().setEntityManager(mock(EntityManager.class)).build(), sessionContext, odata);
when(attribute.isTransient()).thenReturn(true);
when(attribute.getCalculatorConstructor()).thenReturn((Constructor<EdmTransientPropertyCalculator<?>>) constructor);
final Optional<EdmTransientPropertyCalculator<?>> act = cut.getCalculator(attribute);
assertTrue(act.isPresent());
assertNotNull(((TwoParameterTransientPropertyConverter) act.get()).getEntityManager());
assertNotNull(((TwoParameterTransientPropertyConverter) act.get()).getHeader());
}
@Test
void testGetLocaleReturnsValueFromExternalContext() {
cut = new JPAODataInternalRequestContext(JPAODataRequestContext
.with()
.setEntityManager(mock(EntityManager.class))
.setLocales(Arrays.asList(Locale.UK, Locale.ENGLISH))
.build(), sessionContext, odata);
assertEquals(Locale.UK, cut.getLocale());
}
@Test
void testGetLocaleReturnsValueFromExternalContextAfterCopy() throws ODataJPAProcessorException {
cut = new JPAODataInternalRequestContext(JPAODataRequestContext
.with()
.setEntityManager(mock(EntityManager.class))
.setLocales(Arrays.asList(Locale.UK, Locale.ENGLISH))
.build(), sessionContext, odata);
cut = new JPAODataInternalRequestContext(mock(UriInfoResource.class), cut);
assertEquals(Locale.UK, cut.getLocale());
}
private void assertCopied(final JPAODataInternalRequestContext act) {
assertEquals(cut.getEntityManager(), act.getEntityManager());
assertEquals(cut.getClaimsProvider().get(), act.getClaimsProvider().get());
assertEquals(cut.getGroupsProvider().get(), act.getGroupsProvider().get());
}
private void fillContextForCopyConstructor() {
final EntityManager expEm = mock(EntityManager.class);
final JPAODataClaimProvider expCp = new JPAODataClaimsProvider();
final JPAODataGroupProvider expGp = new JPAODataGroupsProvider();
final JPAODataRequestContext context = JPAODataRequestContext
.with()
.setEntityManager(expEm)
.setClaimsProvider(expCp)
.setGroupsProvider(expGp)
.build();
cut = new JPAODataInternalRequestContext(context, sessionContext, odata);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPARequestLinkImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPARequestLinkImplTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
class JPARequestLinkImplTest {
private JPARequestLinkImpl cut;
private JPAAssociationPath path;
private List<JPAOnConditionItem> items;
private JPAConversionHelper helper;
private JPAAssociationAttribute pathLeaf;
private JPAEntityType targetEntityType;
@BeforeEach
void setUp() throws ODataJPAModelException {
helper = new JPAConversionHelper();
items = new ArrayList<>();
path = mock(JPAAssociationPath.class);
pathLeaf = mock(JPAAssociationAttribute.class);
when(path.getJoinColumnsList()).thenReturn(items);
when(path.getTargetType()).thenReturn(targetEntityType);
}
@Test
void testGetEntityType() {
final String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')";
cut = new JPARequestLinkImpl(path, link, helper);
assertEquals(targetEntityType, cut.getEntityType());
}
@Test
void testCreateMultipleStringKeysChildren() throws ODataException {
createAdminDivisionChildrenRelation();
final Map<String, Object> act = cut.getRelatedKeys();
assertNotNull(act);
assertEquals("DE100", act.get("divisionCode"));
assertEquals("NUTS3", act.get("codeID"));
assertEquals("Eurostat", act.get("codePublisher"));
}
@Test
void testCreateMultipleStringValuesChildren() throws ODataException {
createAdminDivisionChildrenRelation();
final Map<String, Object> act = cut.getValues();
assertNotNull(act);
assertEquals("DE100", act.get("parentDivisionCode"));
assertEquals("NUTS3", act.get("parentCodeID"));
assertEquals("Eurostat", act.get("codePublisher"));
}
@Test
void testCreateMultipleStringKeysParent() throws ODataException {
createAdminDivisionParentRelation();
final Map<String, Object> act = cut.getRelatedKeys();
assertNotNull(act);
assertEquals("DE100", act.get("divisionCode"));
assertEquals("NUTS3", act.get("codeID"));
assertEquals("Eurostat", act.get("codePublisher"));
}
@Test
void testCreateMultipleStringValuesParent() throws ODataException {
createAdminDivisionParentRelation();
final Map<String, Object> act = cut.getValues();
assertNotNull(act);
assertEquals("DE100", act.get("parentDivisionCode"));
assertEquals("NUTS3", act.get("parentCodeID"));
assertEquals("Eurostat", act.get("codePublisher"));
}
@Test
void testCreateSingleStringKey() throws ODataException {
final String link = "BusinessPartners('123456')";
cut = new JPARequestLinkImpl(path, link, helper);
completeJPAPath(false);
final Map<String, Object> act = cut.getRelatedKeys();
assertNotNull(act);
assertEquals("123456", act.get("ID"));
}
@Test
void testCreateSingleStringValue() throws ODataException {
final String link = "BusinessPartners('123456')";
cut = new JPARequestLinkImpl(path, link, helper);
completeJPAPath(false);
final Map<String, Object> act = cut.getValues();
assertNotNull(act);
assertEquals("123456", act.get("businessPartnerID"));
}
@Test
void testCreateSingleStringKeyInverse() throws ODataException {
final String link = "BusinessPartners('123456')";
cut = new JPARequestLinkImpl(path, link, helper);
completeJPAPath(true);
final Map<String, Object> act = cut.getRelatedKeys();
assertNotNull(act);
assertEquals("123456", act.get("ID"));
}
@Test
void testCreateSingleStringValueInverse() throws ODataException {
final String link = "BusinessPartners('123456')";
cut = new JPARequestLinkImpl(path, link, helper);
completeJPAPath(true);
final Map<String, Object> act = cut.getValues();
assertNotNull(act);
assertEquals("123456", act.get("businessPartnerID"));
}
@Test
void testCreateSingleStringValueThrowsException() throws ODataException {
final String link = "BusinessPartners('123456')";
when(path.getJoinColumnsList()).thenThrow(ODataJPAModelException.class);
cut = new JPARequestLinkImpl(path, link, helper);
assertThrows(ODataJPAProcessorException.class, () -> cut.getValues());
}
@Test
void testCreateSingleStringKeyThrowsException() throws ODataException {
final String link = "BusinessPartners('123456')";
when(path.getJoinColumnsList()).thenThrow(ODataJPAModelException.class);
cut = new JPARequestLinkImpl(path, link, helper);
assertThrows(ODataJPAProcessorException.class, () -> cut.getRelatedKeys());
}
private void completeJPAPath(final Boolean inverted) throws ODataJPAModelException {
final JPAEntityType targetEt = mock(JPAEntityType.class);
final JPAEntityType sourceEt = mock(JPAEntityType.class);
final JPAAttribute bupaKey = mock(JPAAttribute.class);
final JPAAttribute roleKey1 = mock(JPAAttribute.class);
final JPAAttribute roleKey2 = mock(JPAAttribute.class);
final List<JPAAttribute> bupaKeys = new ArrayList<>();
final List<JPAAttribute> roleKeys = new ArrayList<>();
bupaKeys.add(bupaKey);
roleKeys.add(roleKey1);
roleKeys.add(roleKey2);
when(bupaKey.getInternalName()).thenReturn("ID");
when(bupaKey.getExternalName()).thenReturn("ID");
when(roleKey1.getInternalName()).thenReturn("businessPartnerID");
when(roleKey1.getExternalName()).thenReturn("BusinessPartnerID");
when(roleKey2.getInternalName()).thenReturn("roleCategory");
when(roleKey2.getExternalName()).thenReturn("BusinessPartnerRole");
if (inverted)
items.add(createConditionItem("ID", "ID", "businessPartnerID", "BusinessPartnerID"));
else
items.add(createConditionItem("businessPartnerID", "BusinessPartnerID", "ID", "ID"));
when(path.getLeaf()).thenReturn(pathLeaf);
when(pathLeaf.getInternalName()).thenReturn("businessPartner");
when(path.getTargetType()).thenReturn(targetEt);
when(path.getSourceType()).thenReturn(sourceEt);
when(targetEt.getKey()).thenReturn(bupaKeys);
when(sourceEt.getKey()).thenReturn(roleKeys);
}
private JPAOnConditionItem createConditionItem(final String leftInternalName, final String leftExternalName,
final String rightInternalName, final String rightExternalName) throws ODataJPAModelException {
final JPAOnConditionItem item = mock(JPAOnConditionItem.class);
final JPAPath leftPath = mock(JPAPath.class);
final JPAPath rightPath = mock(JPAPath.class);
when(item.getLeftPath()).thenReturn(leftPath);
when(item.getRightPath()).thenReturn(rightPath);
final JPAAttribute leftAttribute = mock(JPAAttribute.class);
final JPAAttribute rightAttribute = mock(JPAAttribute.class);
when(leftPath.getLeaf()).thenReturn(leftAttribute);
when(rightPath.getLeaf()).thenReturn(rightAttribute);
when(leftAttribute.getInternalName()).thenReturn(leftInternalName);
when(leftAttribute.getExternalName()).thenReturn(leftExternalName);
when(rightAttribute.getInternalName()).thenReturn(rightInternalName);
when(rightAttribute.getExternalName()).thenReturn(rightExternalName);
when(leftAttribute.getEdmType()).thenReturn(EdmPrimitiveTypeKind.String);
when(rightAttribute.getEdmType()).thenReturn(EdmPrimitiveTypeKind.String);
return item;
}
private void createAdminDivisionChildrenRelation() throws ODataJPAModelException {
final String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')";
cut = new JPARequestLinkImpl(path, link, helper);
items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher"));
items.add(createConditionItem("codeID", "CodeID", "parentCodeID", "ParentCodeID"));
items.add(createConditionItem("divisionCode", "DivisionCode", "parentDivisionCode", "ParentDivisionCode"));
}
private void createAdminDivisionParentRelation() throws ODataJPAModelException {
final String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')";
cut = new JPARequestLinkImpl(path, link, helper);
items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher"));
items.add(createConditionItem("parentCodeID", "ParentCodeID", "codeID", "CodeID"));
items.add(createConditionItem("parentDivisionCode", "ParentDivisionCode", "divisionCode", "DivisionCode"));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java | package com.sap.olingo.jpa.processor.core.exception;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey;
class TestODataJPAProcessorException {
// private static String BUNDLE_NAME = "exceptions-i18n";
public static enum MessageKeys implements ODataJPAMessageKey {
RESULT_NOT_FOUND;
@Override
public String getKey() {
return name();
}
}
@Test
void checkSimpleRaiseException() {
try {
RaiseException();
} catch (final ODataApplicationException e) {
assertEquals("No result was fond by Serializer", e.getMessage());
assertEquals(400, e.getStatusCode());
return;
}
fail();
}
@Test
void checkSimpleViaMessageKeyRaiseException() {
try {
RaiseExceptionParam();
} catch (final ODataApplicationException e) {
assertEquals("Unable to convert value 'Willi' of parameter 'Hugo'", e.getMessage());
assertEquals(500, e.getStatusCode());
return;
}
fail();
}
private void RaiseExceptionParam() throws ODataJPAProcessException {
throw new ODataJPADBAdaptorException(ODataJPADBAdaptorException.MessageKeys.PARAMETER_CONVERSION_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, "Willi", "Hugo");
}
private void RaiseException() throws ODataJPAProcessException {
throw new ODataJPASerializerException(ODataJPASerializerException.MessageKeys.RESULT_NOT_FOUND,
HttpStatusCode.BAD_REQUEST);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/AbstractJPAProcessorAttributeTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/AbstractJPAProcessorAttributeTest.java | package com.sap.olingo.jpa.processor.core.properties;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
abstract class AbstractJPAProcessorAttributeTest {
protected JPAPath path;
protected JPAAssociationPath hop;
protected JPAProcessorAttribute cut;
@BeforeEach
void setup() {
path = mock(JPAPath.class);
hop = mock(JPAAssociationPath.class);
when(hop.getAlias()).thenReturn("hophop");
when(path.getAlias()).thenReturn("path");
}
@Test
void testReturnsDescending() {
createCutSortOrder(true);
assertTrue(cut.sortDescending());
}
@Test
void testReturnsAscending() {
createCutSortOrder(false);
assertFalse(cut.sortDescending());
}
@Test
void testGetPathThrowsExceptionIfSetTargetNotCalled() {
createCutSortOrder(true);
assertThrows(IllegalAccessError.class, () -> cut.getPath());
}
protected abstract void createCutSortOrder(boolean descending);
abstract void testJoinRequired();
abstract void testJoinNotRequired();
abstract void testCreateJoinThrowsExceptionIfSetTargetNotCalled();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorSimpleAttributeImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorSimpleAttributeImplTest.java | package com.sap.olingo.jpa.processor.core.properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
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.util.Arrays;
import java.util.Collections;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalArgumentException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
class JPAProcessorSimpleAttributeImplTest extends AbstractJPAProcessorAttributeTest {
@Override
protected void createCutSortOrder(final boolean descending) {
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.emptyList(), descending);
}
@Test
@Override
void testJoinRequired() {
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
assertTrue(cut.requiresJoin());
}
@Test
@Override
void testJoinNotRequired() {
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.emptyList(), true);
assertFalse(cut.requiresJoin());
}
@Test
void testIsSortable() {
when(path.isTransient()).thenReturn(false);
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
assertTrue(cut.isSortable());
}
@Test
void testNotIsSortable() {
when(path.isTransient()).thenReturn(true);
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.emptyList(), true);
assertFalse(cut.isSortable());
}
@Test
void testAliasFromHop() {
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
assertEquals("hophop", cut.getAlias());
}
@Test
void testAliasFromPath() {
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.emptyList(), true);
assertEquals("path", cut.getAlias());
}
@Test
void testExceptionOnMoreThanOneHop() {
final var hop2 = mock(JPAAssociationPath.class);
final ODataJPAIllegalArgumentException act = assertThrows(ODataJPAIllegalArgumentException.class, // NOSONAR
() -> new JPAProcessorSimpleAttributeImpl(path, Arrays.asList(hop, hop2), true));
assertEquals(1, act.getParams().length);
}
@Test
void testCreateJoinReturnsNullIfNotNeeded() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.emptyList(), true);
cut.setTarget(from, Collections.emptyMap(), cb);
assertNull(cut.createJoin());
}
@Test
void testCreateJoin() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("target");
when(from.join("target", JoinType.LEFT)).thenReturn(join);
when(hop.getPath()).thenReturn(Collections.singletonList(target));
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
cut.setTarget(from, Collections.emptyMap(), cb);
final var act = cut.createJoin();
assertEquals(join, act);
}
@Test
void testCreateJoinTakenFromCache() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("target");
when(hop.getPath()).thenReturn(Collections.singletonList(target));
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
cut.setTarget(from, Collections.singletonMap("hophop", join), cb);
final var act = cut.createJoin();
assertEquals(join, act);
verify(from, times(0)).join(anyString(), any());
}
@Test
void testCreateJoinViaNavigation() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var path1 = mock(Join.class);
final var path2 = mock(Join.class);
final var join = mock(Join.class);
final var complex1 = mock(JPAElement.class);
final var complex2 = mock(JPAElement.class);
final var target = mock(JPAElement.class);
when(complex1.getInternalName()).thenReturn("first");
when(complex2.getInternalName()).thenReturn("second");
when(target.getInternalName()).thenReturn("target");
when(from.join(eq("first"), any(JoinType.class))).thenReturn(path1);
when(path1.join(eq("second"), any(JoinType.class))).thenReturn(path2);
when(path2.join("target", JoinType.LEFT)).thenReturn(join);
when(hop.getPath()).thenReturn(Arrays.asList(complex1, complex2, target));
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
cut.setTarget(from, Collections.emptyMap(), cb);
final var act = cut.createJoin();
assertEquals(join, act);
}
// @Test
// void checkFromListOrderByOuterJoinOnConditionOne() throws ODataApplicationException,
// JPANoSelectionException {
// final List<JPAProcessorAttribute> orderBy = new ArrayList<>();
// buildRoleAssociationPath(orderBy);
//
// final Map<String, From<?, ?>> act = cut.createFromClause2(orderBy, new ArrayList<>(), cut.cq, null);
//
// @SuppressWarnings("unchecked")
// final Root<Organization> root = (Root<Organization>) act.get(jpaEntityType.getExternalFQN()
// .getFullQualifiedNameAsString());
// final Set<Join<Organization, ?>> joins = root.getJoins();
// assertEquals(1, joins.size());
//
// for (final Join<Organization, ?> join : joins) {
// assertNull(join.getOn());
// }
// }
@Test
@Override
void testCreateJoinThrowsExceptionIfSetTargetNotCalled() {
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
assertThrows(IllegalAccessError.class, () -> cut.createJoin());
}
@Test
void testGetPath() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("target");
when(from.join("target", JoinType.LEFT)).thenReturn(join);
when(hop.getPath()).thenReturn(Collections.singletonList(target));
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
cut.setTarget(from, Collections.emptyMap(), cb);
assertNotNull(cut.getPath());
}
@Test
void testOrderByOfTransientThrowsException() {
final var cb = mock(CriteriaBuilder.class);
final var attribute = mock(JPAAttribute.class);
when(path.isTransient()).thenReturn(true);
when(path.getLeaf()).thenReturn(attribute);
when(attribute.toString()).thenReturn("Test");
when(path.isPartOfGroups(any())).thenReturn(true);
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
final var act = assertThrows(ODataJPAQueryException.class, () -> cut.createOrderBy(cb, Collections.emptyList()));
assertEquals(400, act.getStatusCode());
}
@Test
void testOrderByNotInGroupsThrowsException() {
final var cb = mock(CriteriaBuilder.class);
final var attribute = mock(JPAAttribute.class);
when(path.isTransient()).thenReturn(false);
when(path.getLeaf()).thenReturn(attribute);
when(attribute.toString()).thenReturn("Test");
when(path.isPartOfGroups(any())).thenReturn(false);
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
final var act = assertThrows(ODataJPAQueryException.class, () -> cut.createOrderBy(cb, Collections.emptyList()));
assertEquals(403, act.getStatusCode());
}
@Test
void testOrderByWithinGroupsOneGroup() throws ODataException {
final var cb = mock(CriteriaBuilder.class);
final var attribute = mock(JPAAttribute.class);
final var groups = Collections.singletonList("Person");
final var from = mock(From.class);
final var attributePath = mock(Path.class);
final var order = mock(Order.class);
when(path.isTransient()).thenReturn(false);
when(path.getLeaf()).thenReturn(attribute);
when(path.getPath()).thenReturn(Collections.singletonList(attribute));
when(attribute.getInternalName()).thenReturn("test");
when(path.isPartOfGroups(groups)).thenReturn(true);
when(from.get("test")).thenReturn(attributePath);
when(cb.desc(any())).thenReturn(order);
when(cb.asc(any())).thenReturn(order);
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.emptyList(), true);
cut.setTarget(from, Collections.emptyMap(), cb);
final var act = cut.createOrderBy(cb, groups);
assertNotNull(act);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/JPAOrderByPropertyFactoryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/JPAOrderByPropertyFactoryTest.java | package com.sap.olingo.jpa.processor.core.properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceCount;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.apache.olingo.server.api.uri.queryoption.OrderByItem;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalArgumentException;
import com.sap.olingo.jpa.processor.core.testmodel.AssociationOneToOneSource;
import com.sap.olingo.jpa.processor.core.testmodel.CollectionDeep;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.util.TestBase;
import com.sap.olingo.jpa.processor.core.util.TestHelper;
class JPAOrderByPropertyFactoryTest extends TestBase {
private JPAOrderByPropertyFactory cut;
private TestHelper testHelper;
private OrderByItem orderByItem;
private JPAEntityType et;
private Member expression;
private UriInfoResource uriInfo;
@BeforeEach
void setup() throws ODataException {
orderByItem = mock(OrderByItem.class);
et = mock(JPAEntityType.class);
expression = mock(Member.class);
uriInfo = mock(UriInfoResource.class);
when(orderByItem.getExpression()).thenReturn(expression);
when(expression.getResourcePath()).thenReturn(uriInfo);
cut = new JPAOrderByPropertyFactory();
testHelper = getHelper();
}
@Test
void testCreatePrimitiveSimpleProperty() throws ODataJPAModelException {
final var property = mock(UriResourcePrimitiveProperty.class);
final var edmType = mock(EdmProperty.class);
when(uriInfo.getUriResourceParts()).thenReturn(Collections.singletonList(property));
when(property.getProperty()).thenReturn(edmType);
when(property.getKind()).thenReturn(UriResourceKind.primitiveProperty);
when(edmType.getName()).thenReturn("Name1");
et = testHelper.getJPAEntityType(Organization.class);
final var act = cut.createProperty(orderByItem, et, Locale.ENGLISH);
assertTrue(act instanceof JPAProcessorSimpleAttribute);
assertTrue(((JPAProcessorSimpleAttribute) act).isSortable());
assertFalse(((JPAProcessorSimpleAttribute) act).requiresJoin());
assertEquals("Name1", act.getAlias());
}
@Test
void testCreateComplexSimpleProperty() throws ODataJPAModelException {
final var complex = mock(UriResourceComplexProperty.class);
final var property = mock(UriResourcePrimitiveProperty.class);
final var edmProperty = mock(EdmProperty.class);
final var edmComplex = mock(EdmProperty.class);
when(uriInfo.getUriResourceParts()).thenReturn(Arrays.asList(complex, property));
when(property.getProperty()).thenReturn(edmProperty);
when(edmProperty.getName()).thenReturn("Region");
when(property.getKind()).thenReturn(UriResourceKind.primitiveProperty);
when(complex.getProperty()).thenReturn(edmComplex);
when(edmComplex.getName()).thenReturn("Address");
et = testHelper.getJPAEntityType(Organization.class);
final var act = cut.createProperty(orderByItem, et, Locale.ENGLISH);
assertTrue(act instanceof JPAProcessorSimpleAttribute);
assertTrue(((JPAProcessorSimpleAttribute) act).isSortable());
assertFalse(((JPAProcessorSimpleAttribute) act).requiresJoin());
assertEquals("Address/Region", act.getAlias());
}
@Test
void testCreateNavigationSimpleProperty() throws ODataJPAModelException {
// "AssociationOneToOneSources?$orderby=ColumnTarget/Source asc"
final var navigation = mock(UriResourceNavigation.class);
final var property = mock(UriResourcePrimitiveProperty.class);
final var edmProperty = mock(EdmProperty.class);
final var edmNavigation = mock(EdmNavigationProperty.class);
when(uriInfo.getUriResourceParts()).thenReturn(Arrays.asList(navigation, property));
when(property.getProperty()).thenReturn(edmProperty);
when(edmProperty.getName()).thenReturn("Source");
when(property.getKind()).thenReturn(UriResourceKind.primitiveProperty);
when(navigation.getProperty()).thenReturn(edmNavigation);
when(edmNavigation.getName()).thenReturn("ColumnTarget");
when(orderByItem.isDescending()).thenReturn(false);
et = testHelper.getJPAEntityType(AssociationOneToOneSource.class);
final var act = cut.createProperty(orderByItem, et, Locale.ENGLISH);
assertTrue(act instanceof JPAProcessorSimpleAttribute);
assertTrue(((JPAProcessorSimpleAttribute) act).isSortable());
assertTrue(((JPAProcessorSimpleAttribute) act).requiresJoin());
assertEquals("ColumnTarget", act.getAlias());
}
@Test
void testCreateNavigationComplexPathProperty() throws ODataJPAModelException {
// "Persons?$orderby=AdministrativeInformation/Created/User/LastName"
final var firstComplex = mock(UriResourceComplexProperty.class);
final var secondComplex = mock(UriResourceComplexProperty.class);
final var edmFirstProperty = mock(EdmProperty.class);
final var edmSecondProperty = mock(EdmProperty.class);
final var navigation = mock(UriResourceNavigation.class);
final var property = mock(UriResourcePrimitiveProperty.class);
final var edmProperty = mock(EdmProperty.class);
final var edmNavigation = mock(EdmNavigationProperty.class);
when(uriInfo.getUriResourceParts()).thenReturn(Arrays.asList(firstComplex, secondComplex, navigation, property));
when(firstComplex.getProperty()).thenReturn(edmFirstProperty);
when(edmFirstProperty.getName()).thenReturn("AdministrativeInformation");
when(secondComplex.getProperty()).thenReturn(edmSecondProperty);
when(edmSecondProperty.getName()).thenReturn("Created");
when(navigation.getProperty()).thenReturn(edmNavigation);
when(edmNavigation.getName()).thenReturn("User");
when(property.getProperty()).thenReturn(edmProperty);
when(edmProperty.getName()).thenReturn("LastName");
when(property.getKind()).thenReturn(UriResourceKind.primitiveProperty);
when(orderByItem.isDescending()).thenReturn(false);
et = testHelper.getJPAEntityType(Person.class);
final var act = cut.createProperty(orderByItem, et, Locale.ENGLISH);
assertTrue(act instanceof JPAProcessorSimpleAttribute);
assertTrue(((JPAProcessorSimpleAttribute) act).isSortable());
assertTrue(((JPAProcessorSimpleAttribute) act).requiresJoin());
assertEquals("AdministrativeInformation/Created/User", act.getAlias());
}
@Test
void testCreateNavigationCount() throws ODataJPAModelException {
// "Organizations?$orderby=Roles/$count"
final var navigation = mock(UriResourceNavigation.class);
final var count = mock(UriResourceCount.class);
final var edmNavigation = mock(EdmNavigationProperty.class);
when(uriInfo.getUriResourceParts()).thenReturn(Arrays.asList(navigation, count));
when(navigation.getProperty()).thenReturn(edmNavigation);
when(edmNavigation.getName()).thenReturn("Roles");
when(count.getKind()).thenReturn(UriResourceKind.count);
when(orderByItem.isDescending()).thenReturn(false);
et = testHelper.getJPAEntityType(Organization.class);
final var act = cut.createProperty(orderByItem, et, Locale.ENGLISH);
assertTrue(act instanceof JPAProcessorCountAttribute);
assertTrue(((JPAProcessorCountAttribute) act).isSortable());
assertTrue(((JPAProcessorCountAttribute) act).requiresJoin());
assertEquals("Roles", act.getAlias());
}
@Test
void testCreatePrimitiveCollectionCountViaComplex() throws ODataJPAModelException {
// "CollectionDeeps?$orderby=FirstLevel/SecondLevel/Comment/$count asc"
final var firstComplex = mock(UriResourceComplexProperty.class);
final var secondComplex = mock(UriResourceComplexProperty.class);
final var edmFirstProperty = mock(EdmProperty.class);
final var edmSecondProperty = mock(EdmProperty.class);
when(firstComplex.getProperty()).thenReturn(edmFirstProperty);
when(edmFirstProperty.getName()).thenReturn("FirstLevel");
when(secondComplex.getProperty()).thenReturn(edmSecondProperty);
when(edmSecondProperty.getName()).thenReturn("SecondLevel");
final var collection = mock(UriResourcePrimitiveProperty.class);
final var edmCollection = mock(EdmProperty.class);
final var count = mock(UriResourceCount.class);
when(uriInfo.getUriResourceParts()).thenReturn(Arrays.asList(firstComplex, secondComplex, collection, count));
when(collection.getProperty()).thenReturn(edmCollection);
when(collection.isCollection()).thenReturn(true);
when(edmCollection.getName()).thenReturn("Comment");
when(count.getKind()).thenReturn(UriResourceKind.count);
when(orderByItem.isDescending()).thenReturn(false);
et = testHelper.getJPAEntityType(CollectionDeep.class);
final var act = cut.createProperty(orderByItem, et, Locale.ENGLISH);
assertTrue(act instanceof JPAProcessorCountAttribute);
assertTrue(((JPAProcessorCountAttribute) act).isSortable());
assertTrue(((JPAProcessorCountAttribute) act).requiresJoin());
assertEquals("FirstLevel/SecondLevel/Comment", act.getAlias());
}
@Test
void testCreateComplexCollectionCountViaComplex() throws ODataJPAModelException {
// "CollectionDeeps?$orderby=FirstLevel/SecondLevel/Address/$count asc"
final var firstComplex = mock(UriResourceComplexProperty.class);
final var secondComplex = mock(UriResourceComplexProperty.class);
final var edmFirstProperty = mock(EdmProperty.class);
final var edmSecondProperty = mock(EdmProperty.class);
when(firstComplex.getProperty()).thenReturn(edmFirstProperty);
when(edmFirstProperty.getName()).thenReturn("FirstLevel");
when(secondComplex.getProperty()).thenReturn(edmSecondProperty);
when(edmSecondProperty.getName()).thenReturn("SecondLevel");
final var collection = mock(UriResourceComplexProperty.class);
final var edmCollection = mock(EdmProperty.class);
final var count = mock(UriResourceCount.class);
when(uriInfo.getUriResourceParts()).thenReturn(Arrays.asList(firstComplex, secondComplex, collection, count));
when(collection.getProperty()).thenReturn(edmCollection);
when(collection.isCollection()).thenReturn(true);
when(edmCollection.getName()).thenReturn("Address");
when(count.getKind()).thenReturn(UriResourceKind.count);
when(orderByItem.isDescending()).thenReturn(false);
et = testHelper.getJPAEntityType(CollectionDeep.class);
final var act = cut.createProperty(orderByItem, et, Locale.ENGLISH);
assertTrue(act instanceof JPAProcessorCountAttribute);
assertTrue(((JPAProcessorCountAttribute) act).isSortable());
assertTrue(((JPAProcessorCountAttribute) act).requiresJoin());
assertEquals("FirstLevel/SecondLevel/Address", act.getAlias());
}
@Test
void testCreateDescriptionSimpleProperty() throws ODataJPAModelException {
final var property = mock(UriResourcePrimitiveProperty.class);
final var edmType = mock(EdmProperty.class);
when(uriInfo.getUriResourceParts()).thenReturn(Collections.singletonList(property));
when(property.getProperty()).thenReturn(edmType);
when(property.getKind()).thenReturn(UriResourceKind.primitiveProperty);
when(edmType.getName()).thenReturn("LocationName");
et = testHelper.getJPAEntityType(Organization.class);
final var act = cut.createProperty(orderByItem, et, Locale.ENGLISH);
assertTrue(act instanceof JPAProcessorDescriptionAttribute);
assertTrue(((JPAProcessorDescriptionAttribute) act).isSortable());
assertTrue(((JPAProcessorDescriptionAttribute) act).requiresJoin());
assertEquals("LocationName", act.getAlias());
}
@Test
void testThrowsBadRequestExceptionOnUnknownProperty() throws ODataJPAModelException {
final var property = mock(UriResourcePrimitiveProperty.class);
final var edmType = mock(EdmProperty.class);
when(uriInfo.getUriResourceParts()).thenReturn(Collections.singletonList(property));
when(property.getProperty()).thenReturn(edmType);
when(property.getKind()).thenReturn(UriResourceKind.primitiveProperty);
when(edmType.getName()).thenReturn("Name");
et = testHelper.getJPAEntityType(Organization.class);
assertThrows(ODataJPAIllegalArgumentException.class,
() -> cut.createProperty(orderByItem, et, Locale.ENGLISH));
}
@Test
void testThrowsNotImplementedOnOrderByFunction() {
final var function = mock(UriResourceFunction.class);
final var edmType = mock(EdmFunction.class);
when(uriInfo.getUriResourceParts()).thenReturn(Collections.singletonList(function));
when(function.getFunction()).thenReturn(edmType);
when(function.getKind()).thenReturn(UriResourceKind.function);
when(edmType.getName()).thenReturn("Name");
assertThrows(ODataJPAIllegalArgumentException.class,
() -> cut.createProperty(orderByItem, et, Locale.ENGLISH));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorCountAttributeImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorCountAttributeImplTest.java | package com.sap.olingo.jpa.processor.core.properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
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.util.Arrays;
import java.util.Collections;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalArgumentException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
class JPAProcessorCountAttributeImplTest extends AbstractJPAProcessorAttributeTest {
@Override
protected void createCutSortOrder(final boolean descending) {
cut = new JPAProcessorCountAttributeImpl(Collections.emptyList(), descending);
}
@Test
@Override
void testJoinRequired() {
cut = new JPAProcessorCountAttributeImpl(Collections.singletonList(hop), true);
assertTrue(cut.requiresJoin());
}
@Test
@Override
void testJoinNotRequired() {
cut = new JPAProcessorCountAttributeImpl(Collections.emptyList(), true);
assertFalse(cut.requiresJoin());
}
@Test
void testIsSortable() {
final var association = mock(JPAAssociationAttribute.class);
when(association.isTransient()).thenReturn(false);
when(hop.getLeaf()).thenReturn(association);
cut = new JPAProcessorCountAttributeImpl(Collections.singletonList(hop), true);
assertTrue(cut.isSortable());
}
@Test
void testNotIsSortableNoHop() {
cut = new JPAProcessorCountAttributeImpl(Collections.emptyList(), true);
assertFalse(cut.isSortable());
}
@Test
void testNotIsSortableTransient() {
final var association = mock(JPAAssociationAttribute.class);
when(association.isTransient()).thenReturn(true);
when(hop.getLeaf()).thenReturn(association);
cut = new JPAProcessorCountAttributeImpl(Collections.singletonList(hop), true);
assertFalse(cut.isSortable());
}
@Test
void testAliasFromHop() {
cut = new JPAProcessorCountAttributeImpl(Collections.singletonList(hop), true);
assertEquals("hophop", cut.getAlias());
}
@Test
void testAliasNoHop() {
cut = new JPAProcessorCountAttributeImpl(Collections.emptyList(), true);
assertEquals("Count", cut.getAlias());
}
@Test
void testExceptionOnMoreThanOneHop() {
final var hop2 = mock(JPAAssociationPath.class);
final ODataJPAIllegalArgumentException act = assertThrows(ODataJPAIllegalArgumentException.class, // NOSONAR
() -> new JPAProcessorCountAttributeImpl(Arrays.asList(hop, hop2), true));
assertEquals(1, act.getParams().length);
}
@Test
void testCreateJoinReturnsNullIfNotNeeded() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
cut = new JPAProcessorCountAttributeImpl(Collections.emptyList(), true);
cut.setTarget(from, Collections.emptyMap(), cb);
assertNull(cut.createJoin());
}
@Test
void testCreateJoin() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("target");
when(from.join("target", JoinType.LEFT)).thenReturn(join);
when(hop.getPath()).thenReturn(Collections.singletonList(target));
cut = new JPAProcessorCountAttributeImpl(Collections.singletonList(hop), true);
cut.setTarget(from, Collections.emptyMap(), cb);
final var act = cut.createJoin();
assertEquals(join, act);
}
@Test
void testCreateJoinTakenFromCache() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("target");
when(hop.getPath()).thenReturn(Collections.singletonList(target));
cut = new JPAProcessorCountAttributeImpl(Collections.singletonList(hop), true);
cut.setTarget(from, Collections.singletonMap("hophop", join), cb);
final var act = cut.createJoin();
assertEquals(join, act);
verify(from, times(0)).join(anyString(), any());
}
@Test
@Override
void testCreateJoinThrowsExceptionIfSetTargetNotCalled() {
cut = new JPAProcessorCountAttributeImpl(Collections.singletonList(hop), true);
assertThrows(IllegalAccessError.class, () -> cut.createJoin());
}
@Test
void testOrderByOfTransientThrowsException() {
final var cb = mock(CriteriaBuilder.class);
final var attribute = mock(JPAAttribute.class);
when(hop.getPath()).thenReturn(Collections.singletonList(attribute));
when(attribute.toString()).thenReturn("Test");
when(attribute.isTransient()).thenReturn(true);
cut = new JPAProcessorCountAttributeImpl(Collections.singletonList(hop), true);
final var act = assertThrows(ODataJPAQueryException.class, () -> cut.createOrderBy(cb, Collections.emptyList()));
assertEquals(501, act.getStatusCode());
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorDescriptionAttributeImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorDescriptionAttributeImplTest.java | package com.sap.olingo.jpa.processor.core.properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
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.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Stream;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADescriptionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalArgumentException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
class JPAProcessorDescriptionAttributeImplTest extends AbstractJPAProcessorAttributeTest {
@Override
protected void createCutSortOrder(final boolean descending) {
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), descending, Locale.ENGLISH);
}
@Test
@Override
void testJoinRequired() {
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), false, Locale.ENGLISH);
assertTrue(cut.requiresJoin());
}
@Override
void testJoinNotRequired() {
// Description Properties allays require join
}
@Test
void testIsSortable() {
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.ENGLISH);
assertTrue(cut.isSortable());
}
@Test
void testAliasFromPath() {
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.UK);
assertEquals("path", cut.getAlias());
}
@Test
void testExceptionOnMoreThanOneHop() {
final var hop2 = mock(JPAAssociationPath.class);
final ODataJPAIllegalArgumentException act = assertThrows(ODataJPAIllegalArgumentException.class, // NOSONAR
() -> new JPAProcessorDescriptionAttributeImpl(path, Arrays.asList(hop, hop2), true, Locale.ENGLISH));
assertEquals(1, act.getParams().length);
}
private static Stream<Arguments> provideJoinPreconditions() {
return Stream.of(
Arguments.of(true),
Arguments.of(false));
}
@ParameterizedTest
@MethodSource("provideJoinPreconditions")
void testCreateJoin(final boolean isLocale) {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var localePath = createLocaleFiledPath(join);
createDescriptionProperty(isLocale, localePath);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("description");
when(from.join("description", JoinType.LEFT)).thenReturn(join);
when(hop.getPath()).thenReturn(Collections.singletonList(target));
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.UK);
cut.setTarget(from, Collections.emptyMap(), cb);
final var act = cut.createJoin();
assertEquals(join, act);
verify(cb).equal(localePath.right, isLocale ? Locale.UK.toString() : Locale.UK.getLanguage());
}
@Test
void testCreateJoinWithOnCondition() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var onCondition = mock(Predicate.class);
final var localeOnCondition = mock(Predicate.class);
final var localePath = createLocaleFiledPath(join);
createDescriptionProperty(true, localePath);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("description");
when(from.join("description", JoinType.LEFT)).thenReturn(join);
when(hop.getPath()).thenReturn(Collections.singletonList(target));
when(join.getOn()).thenReturn(onCondition);
when(cb.equal(localePath.right, Locale.UK.toString())).thenReturn(localeOnCondition);
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.UK);
cut.setTarget(from, Collections.emptyMap(), cb);
final var act = cut.createJoin();
assertEquals(join, act);
verify(cb).and(onCondition, localeOnCondition);
}
@Test
void testCreateJoinWithFixedValues() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var localeOnCondition = mock(Predicate.class);
final ImmutablePair<Map<Path<Object>, String>, Map<JPAPath, String>> fixedValues = getFixValues(join);
final var localePath = createLocaleFiledPath(join);
final var descriptionProperty = createDescriptionProperty(true, localePath);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("description");
when(from.join("description", JoinType.LEFT)).thenReturn(join);
when(hop.getPath()).thenReturn(Collections.singletonList(target));
when(descriptionProperty.getFixedValueAssignment()).thenReturn(fixedValues.right);
when(cb.equal(localePath.right, Locale.UK.toString())).thenReturn(localeOnCondition);
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.UK);
cut.setTarget(from, Collections.emptyMap(), cb);
final var act = cut.createJoin();
assertEquals(join, act);
for (final var fixValue : fixedValues.left.entrySet())
verify(cb).equal(fixValue.getKey(), fixValue.getValue());
}
@Test
@Override
void testCreateJoinThrowsExceptionIfSetTargetNotCalled() {
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.UK);
assertThrows(IllegalAccessError.class, () -> cut.createJoin());
}
@Test
void testGetPath() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var localePath = createLocaleFiledPath(join);
final JPADescriptionAttribute attribute = createDescriptionProperty(false, localePath);
final JPAAttribute descriptionAttribute = mock(JPAAttribute.class);
when(path.getLeaf()).thenReturn(attribute);
when(attribute.getDescriptionAttribute()).thenReturn(descriptionAttribute);
when(descriptionAttribute.getInternalName()).thenReturn("name");
final var criteriaPath = mock(Path.class);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("description");
when(from.join("description", JoinType.LEFT)).thenReturn(join);
when(hop.getPath()).thenReturn(Collections.singletonList(target));
when(join.get("name")).thenReturn(criteriaPath);
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.UK);
cut.setTarget(from, Collections.emptyMap(), cb);
assertNotNull(cut.getPath());
assertEquals(criteriaPath, cut.getPath());
}
@Test
void testCreateJoinTakenFromCache() {
final var cb = mock(CriteriaBuilder.class);
final var from = mock(From.class);
final var join = mock(Join.class);
final var target = mock(JPAElement.class);
when(target.getInternalName()).thenReturn("target");
when(hop.getPath()).thenReturn(Collections.singletonList(target));
cut = new JPAProcessorSimpleAttributeImpl(path, Collections.singletonList(hop), true);
cut.setTarget(from, Collections.singletonMap("hophop", join), cb);
final var act = cut.createJoin();
assertEquals(join, act);
verify(from, times(0)).join(anyString(), any());
}
@Test
void testOrderByOfTransientThrowsException() {
final var cb = mock(CriteriaBuilder.class);
final var attribute = mock(JPAAttribute.class);
when(path.isTransient()).thenReturn(true);
when(path.getLeaf()).thenReturn(attribute);
when(attribute.toString()).thenReturn("Test");
when(path.isPartOfGroups(any())).thenReturn(true);
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.UK);
final var act = assertThrows(ODataJPAQueryException.class, () -> cut.createOrderBy(cb, Collections.emptyList()));
assertEquals(400, act.getStatusCode());
}
@Test
void testOrderByNotInGroupsThrowsException() {
final var cb = mock(CriteriaBuilder.class);
final var attribute = mock(JPAAttribute.class);
when(path.isTransient()).thenReturn(false);
when(path.getLeaf()).thenReturn(attribute);
when(attribute.toString()).thenReturn("Test");
when(path.isPartOfGroups(any())).thenReturn(false);
cut = new JPAProcessorDescriptionAttributeImpl(path, Collections.emptyList(), true, Locale.UK);
final var act = assertThrows(ODataJPAQueryException.class, () -> cut.createOrderBy(cb, Collections.emptyList()));
assertEquals(403, act.getStatusCode());
}
private ImmutablePair<Map<Path<Object>, String>, Map<JPAPath, String>>
getFixValues(final Join<?, ?> join) {
final Map<Path<Object>, String> fixedPath = new HashMap<>();
final Map<JPAPath, String> fixedValues = new HashMap<>();
final var valueOnePath = getFixValue(join, "one");
final var valueTwoPath = getFixValue(join, "two");
fixedValues.put(valueOnePath.right, "One");
fixedPath.put(valueOnePath.left, "One");
fixedValues.put(valueTwoPath.right, "Two");
fixedPath.put(valueTwoPath.left, "Two");
return new ImmutablePair<>(fixedPath, fixedValues);
}
@SuppressWarnings("unchecked")
private ImmutablePair<Path<Object>, JPAPath> getFixValue(final Join<?, ?> join, final String name) {
final var valueOnePath = mock(JPAPath.class);
final var valueOneElement = mock(JPAElement.class);
final var valueOneExpression = mock(Path.class);
when(valueOneElement.getInternalName()).thenReturn(name);
when(valueOnePath.getPath()).thenReturn(Collections.singletonList(valueOneElement));
when(join.get(name)).thenReturn(valueOneExpression);
return new ImmutablePair<>(valueOneExpression, valueOnePath);
}
protected JPADescriptionAttribute createDescriptionProperty(final boolean isLocale,
final ImmutablePair<JPAPath, Path<Object>> localePath) {
final var descriptionProperty = mock(JPADescriptionAttribute.class);
when(descriptionProperty.getLocaleFieldName()).thenReturn(localePath.left);
when(descriptionProperty.isLocationJoin()).thenReturn(isLocale);
when(descriptionProperty.getInternalName()).thenReturn("description");
when(path.getLeaf()).thenReturn(descriptionProperty);
when(path.getPath()).thenReturn(Arrays.asList(descriptionProperty));
return descriptionProperty;
}
@SuppressWarnings("unchecked")
private ImmutablePair<JPAPath, Path<Object>> createLocaleFiledPath(final Join<?, ?> join) {
final var complex = mock(JPAElement.class);
final var locale = mock(JPAElement.class);
final var path = mock(JPAPath.class);
final var complexPath = mock(Path.class);
final var localePath = mock(Path.class);
when(path.getPath()).thenReturn(Arrays.asList(complex, locale));
when(complex.getInternalName()).thenReturn("complex");
when(locale.getInternalName()).thenReturn("locale");
when(join.get("complex")).thenReturn(complexPath);
when(complexPath.get("locale")).thenReturn(localePath);
return new ImmutablePair<>(path, localePath);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.