VDM для интеграционных тестов - PullRequest
1 голос
/ 05 июня 2019

Я использовал VDM, чтобы использовать внешний ODATA-сервис.Работает хорошо.Теперь я пытаюсь использовать VDM для тестирования интеграции, чтобы протестировать созданный сервис ODATA с использованием модели CAP.

Я использовал restTemplate.exchange () в тесте интеграции для тестирования сервиса ODATA.Это работало хорошо.Теперь я решил пойти с SDK VDM подход.Файлы VDM были сгенерированы успешно.Но при попытке запустить интеграционные тесты происходит сбой с исключением

com.sap.cloud.sdk.cloudplatform.exception.ShouldNotHappenException: java.lang.NullPointerException: при попытке вызвать метод com.google.gson.JsonObject.get (java.lang.String) пустого объекта, загруженного из локальной переменной 'xsuaaServiceCredentials'

Я передаю локальный токен JWT, а также набор VCAP_SERVICES в переменной среды.

package com.sap.crun.landscape;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;

import com.sap.cloud.sdk.odatav2.connectivity.ODataException;
import com.sap.cloud.sdk.s4hana.connectivity.ErpConfigContext;
import com.sap.cloud.sdk.testutil.MockUtil;

import com.sap.crun.landscape.vdm.odatalandscapeservice.namespaces.odatalandscapeservice.LandscapeObjects;
import com.sap.crun.landscape.vdm.odatalandscapeservice.namespaces.odatalandscapeservice.LandscapeObjectsCreateFluentHelper;
import com.sap.crun.landscape.vdm.odatalandscapeservice.namespaces.odatalandscapeservice.LandscapeObjectsFluentHelper;
import com.sap.crun.landscape.vdm.odatalandscapeservice.namespaces.odatalandscapeservice.Properties;
import com.sap.crun.landscape.vdm.odatalandscapeservice.services.DefaultOdataLandscapeserviceService;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = { TestApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:LmsTest.properties")
public class BusinessServiceIT {

    private static final Logger LOG = CloudLoggerFactory.getLogger(LisImporter.class);
    private static final MockUtil mockUtil = new MockUtil();
    private static final DefaultOdataLandscapeserviceService lmsService = new DefaultOdataLandscapeserviceService()
            .withServicePath("/odata/v2/LandscapeService");
    private ErpConfigContext erpConfCtx;
    private static final String jwToken = new JwtGenerator()
            .getTokenForAuthorizationHeader(LocalSecurityConfig.XSAPPNAME + ".d", LocalSecurityConfig.XSAPPNAME + ".r", LocalSecurityConfig.XSAPPNAME + ".a");
    private static final LandscapeObjectsFluentHelper lsoCreateHelper = lmsService.getAllLandscapeObjects();

    @Autowired
    private WebApplicationContext context;

    @LocalServerPort
    int randomServerPort;


    @BeforeClass
    public static void beforeClass() {
        mockUtil.mockDefaults();
        mockUtil.mockAuditLog();

        lsoCreateHelper
        .withCustomHttpHeader("Authorization", new JwtGenerator().getTokenForAuthorizationHeader(
                LocalSecurityConfig.XSAPPNAME + ".d", LocalSecurityConfig.XSAPPNAME + ".a", LocalSecurityConfig.XSAPPNAME + ".r"))
        .onRequestAndImplicitRequests();

    }

    @Before
    public void beforeEach() throws URISyntaxException {
        mockUtil.mockDestination("localhorst", new URI("http://localhost:" + randomServerPort));
        erpConfCtx = new ErpConfigContext("localhorst");
    }

    @Test
    public void parseVcapServices() {
        final SAPPropertyPlaceholderConfigurer propertyHolder = new SAPPropertyPlaceholderConfigurer();
        final String xsappname = propertyHolder.readVcapServices(SAPPropertyPlaceholderConfigurer.propertyXsAppname,
                "application");
        assertEquals(LocalSecurityConfig.XSAPPNAME, xsappname);
    }

    @Test
    public void createBusinessService() {


        Properties properties = new Properties();
        List<Properties> propertySet = new ArrayList<>();
        properties.setName("useCase");
        properties.setValue("XX");
        properties.setSource("XXX");
        propertySet.add(properties);

        LandscapeObjects landscapeObjects = new LandscapeObjects(null, null, null, null, null, "benufromit", "benufromit_test", BusinessService.name(), "123", "LMS", null, null, propertySet);
        LOG.info("benu-business1");

        final LandscapeObjectsCreateFluentHelper lsoCreateHelper = lmsService.createLandscapeObjects(landscapeObjects)
                .withCustomHttpHeader("Authorization", new JwtGenerator().getTokenForAuthorizationHeader(
                        LocalSecurityConfig.XSAPPNAME + ".d", LocalSecurityConfig.XSAPPNAME + ".a")).onRequestAndImplicitRequests();

        try {
            lsoCreateHelper.execute(erpConfCtx); //It fails here
            LOG.info("benu-business3 {}", landscapeObjects.getId());
        } catch (ODataException e) {
            e.printStackTrace();
        }

    }
}

Трассировка стека

 com.sap.cloud.sdk.cloudplatform.exception.ShouldNotHappenException: java.lang.NullPointerException: while trying to invoke the method com.google.gson.JsonObject.get(java.lang.String) of a null object loaded from local variable 'xsuaaServiceCredentials'
                   at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextServletFilter.doFilter(RequestContextServletFilter.java:216) ~[servlet-2.15.0.jar:na]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176) ~[spring-security-oauth2-2.0.16.RELEASE.jar:na]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
                   at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:685) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_202]
                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_202]
                   at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at java.lang.Thread.run(Thread.java:836) [na:1.8.0_202] Caused by: java.lang.NullPointerException: while trying to invoke the method com.google.gson.JsonObject.get(java.lang.String) of a null object loaded from local variable 'xsuaaServiceCredentials'
                   at com.sap.cloud.sdk.cloudplatform.security.AuthTokenDecoder.getVerificationPublicKey(AuthTokenDecoder.java:86) ~[security-scp-cf-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.security.AuthTokenDecoder.decode(AuthTokenDecoder.java:146) ~[security-scp-cf-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.security.AuthTokenDecoder.decode(AuthTokenDecoder.java:195) ~[security-scp-cf-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.security.AuthTokenRequestContextListener.getProperties(AuthTokenRequestContextListener.java:49) ~[security-scp-cf-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.servlet.AbstractRequestContextListener.requestContextInitialized(AbstractRequestContextListener.java:40) ~[servlet-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextCallable.notifyContextInitialized(RequestContextCallable.java:68) ~[servlet-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextCallable.call(RequestContextCallable.java:129) ~[servlet-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextServletFilter.doFilter(RequestContextServletFilter.java:209) ~[servlet-2.15.0.jar:na]
                   ... 76 common frames omitted

1 Ответ

0 голосов
/ 05 июня 2019

Обновленный ответ:

После вызова мы пришли к выводу, что метод не был корректно смоделирован во время выполнения теста.

Пожалуйста, добавьте следующие строки кода в свой интеграционный тест с аннотацией @Before:

final String publicKey = "...";
final Map<String,String> verificationkey = ImmutableMap.of("verificationkey", publicKey);
final JsonObject xsuaaServiceCredentials = new Gson().toJsonTree(verificationkey).getAsJsonObject();
Mockito.when(((ScpCfCloudPlatform) CloudPlatformAccessor.getCloudPlatform()).getXsuaaServiceCredentials(ArgumentMatchers.any(DecodedJWT.class))).thenReturn(xsuaaServiceCredentials);

Это обеспечит правильную проверку протестированного приложения предоставленного токена аутентификации с подготовленным открытым ключом.

Я отправил этот сценарий нашей команде разработчиков, чтобы рассмотреть исправление этого потенциального пробела в функции.


Устаревший ответ:

Некоторые открытые точки для анализа проблемы:

  1. Используете ли вы Cloud SDK только для тестирования или также в бэкэнде приложения?

  2. Имеется в виду подсказка; Я бы не использовал try-catch в тестовом коде.

  3. Рекомендуется создавать выделенный ErpConfigContext для каждого теста. Также, пожалуйста, используйте RequestContextExecutor :

    import com.sap.cloud.sdk.cloudplatform.servlet.RequestContextExecutor;
    

    с

    @Test
    public void createBusinessService() {
      new RequestContextExecutor().execute(() -> {
        ...
        lsoCreateHelper.execute(new ErpConfigContext("localhorst"));
        ...
      });
    }
    

Это работает или дает вам другое сообщение?

...