如何在Jenkins上解决wiremock问题?java.net.BindException:权限被拒绝

ymdaylpp  于 2023-10-17  发布在  Jenkins
关注(0)|答案(1)|浏览(122)

我有问题与wiremock测试失败的Jenkins。当我尝试在本地运行它时,它运行得很顺利,但当我尝试在Jenkins上运行时,出现了以下异常:

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] ============================

[2023-10-09T12:20:41.562Z] CONDITIONS EVALUATION REPORT

[2023-10-09T12:20:41.562Z] ============================

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] Positive matches:

[2023-10-09T12:20:41.562Z] -----------------

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z]     None

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] Negative matches:

[2023-10-09T12:20:41.562Z] -----------------

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z]     None

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] Exclusions:

[2023-10-09T12:20:41.562Z] -----------

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z]     None

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] Unconditional classes:

[2023-10-09T12:20:41.562Z] ----------------------

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z]     None

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.562Z] 

[2023-10-09T12:20:41.670Z] [ThreadedStreamConsumer] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - Tests run: 7, Failures: 0, Errors: 7, Skipped: 0, Time elapsed: 48.407 s <<< FAILURE! - in com.dhl.subscriptions.boot.controller.NotificationsControllerITest

[2023-10-09T12:20:41.671Z] [ThreadedStreamConsumer] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - testUpdateNotificationRuleStatus  Time elapsed: 0 s  <<< ERROR!

[2023-10-09T12:20:41.761Z] java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@1845761c testClass = com.dhl.subscriptions.boot.controller.NotificationsControllerITest, locations = [], classes = [com.dhl.subscriptions.boot.SubscriptionsApplication], contextInitializerClasses = [], activeProfiles = ["test"], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true"], contextCustomizers = [[ImportsContextCustomizer@733f04ae key = [org.springframework.cloud.contract.wiremock.WireMockConfiguration, org.springframework.cloud.contract.wiremock.WireMockRestTemplateConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@497570fb, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@51e37590, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@43255a5b, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@1c6e0a08, org.springframework.boot.test.web.reactive.server.WebTestClientContextCustomizer@433e536f, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@81319d4a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5a9800f8, org.springframework.boot.test.context.SpringBootTestAnnotation@fecd68b1], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]

[2023-10-09T12:20:41.761Z] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.contract.wiremock.WireMockConfiguration': Invocation of init method failed

[2023-10-09T12:20:41.761Z] Caused by: com.github.tomakehurst.wiremock.common.FatalStartupException: java.lang.RuntimeException: java.io.IOException: Failed to bind to /0.0.0.0:99

[2023-10-09T12:20:41.762Z] Caused by: java.lang.RuntimeException: java.io.IOException: Failed to bind to /0.0.0.0:99

[2023-10-09T12:20:41.762Z] Caused by: java.io.IOException: Failed to bind to /0.0.0.0:99

[2023-10-09T12:20:41.762Z] Caused by: java.net.BindException: Permission denied

[2023-10-09T12:20:41.762Z] 

[2023-10-09T12:20:41.762Z] [ThreadedStreamConsumer] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - testGetNotificationRule  Time elapsed: 0 s  <<< ERROR!

JUnit代码是:

package com.dhl.subscriptions.boot.controller;

import com.dhl.security.aaa.adapter.keycloak.Authentication;
import com.dhl.security.model.User;
import com.dhl.subscriptions.boot.SubscriptionsApplication;
import com.dhl.subscriptions.db.entity.NotificationConfigEntity;
import com.dhl.subscriptions.db.entity.NotificationRuleEntity;
import com.dhl.subscriptions.db.entity.TagsEntity;
import com.dhl.subscriptions.db.entity.UserProfileEntity;
import com.dhl.subscriptions.db.repository.NotificationConfigRepository;
import com.dhl.subscriptions.db.repository.NotificationRuleRepository;
import com.dhl.subscriptions.db.repository.UserProfileRepository;
import com.dhl.subscriptions.db.repository.UserTagRepository;
import com.dhl.subscriptions.model.*;
import com.dhl.subscriptions.rest.api.NotificationsController;
import com.dhl.subscriptions.service.NaritaOperations;
import com.dhl.subscriptions.service.NaritaService;
import com.dhl.subscriptions.service.NotificationService;
import com.dhl.subscriptions.service.config.ConfigService;
import com.dhl.subscriptions.service.mapper.NotificationRuleMapper;
import com.dhl.track.commons.translations.TranslationsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.Hibernate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.dhl.subscriptions.boot.controller.DataUtil.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = SubscriptionsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles({"test"})
@AutoConfigureWireMock(port = 99, stubs = {"classpath:/stubs"})
public class NotificationsControllerITest {
    public static final String USER_EMAIL = "[email protected]";

    @Autowired
    private UserProfileRepository userProfileRepository;
    @Autowired
    private NotificationConfigRepository notificationConfigRepository;
    @Autowired
    private NotificationRuleRepository notificationRuleRepository;
    @Autowired
    private NaritaService naritaService;
    @Autowired
    private NotificationRuleMapper notificationRuleMapper;
    @MockBean
    private Authentication authentication;
    @Autowired
    private UserTagRepository userTagRepository;
    @Autowired
    private NaritaOperations naritaOperations;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private TranslationsService translationsService;
    @Autowired
    private ConfigService configService;

    @Autowired
    private NotificationsController notificationsController;

    private MockMvc mockMvc;

    @Test
    public void testGetConfigMap() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(notificationsController).build();

        try {
            MvcResult result = this.mockMvc.perform(
                    get("/notifications/GENERAL")
                            .contentType(MediaType.APPLICATION_JSON)

            ).andReturn();

            assertNotNull(result);
            assertEquals("{\"setting\":\"GENERAL\",\"text\":\"notification.type_general\",\"type\":{\"text\":\"notification.shipments_affected\",\"value\":{\"fe_type\":\"choice\",\"from_values\":[{\"text\":\"notification.shipments_affected_all\",\"value\":\"ALL\"},{\"text\":\"notification.shipments_affected_favorites\",\"value\":\"FAVORITES\"}]}},\"events\":{\"text\":\"notification.events\",\"values\":{\"fe_type\":\"multi_choice\",\"from_values\":[{\"event_type\":\"common\",\"text\":\"notification.triggering_events_status\",\"tooltip\":\"notification.triggering_events_status_tooltip\",\"value\":\"STATUS_CHANGED\",\"default\":true},{\"event_type\":\"common\",\"text\":\"notification.triggering_events_irregularities\",\"tooltip\":\"notification.triggering_events_irregularities_tooltip\",\"value\":\"OPERATIONAL_IRREGULARITIES\",\"default\":true},{\"event_type\":\"milestone\",\"text\":\"notification.triggering_events_pickup\",\"value\":\"PICKUP\"},{\"event_type\":\"milestone\",\"text\":\"notification.triggering_events_export_customs_clearance\",\"value\":\"EXPORT_CUSTOMS_CLEARANCE\"},{\"event_type\":\"milestone\",\"text\":\"notification.triggering_events_origin\",\"value\":\"ORIGIN_PORT\"},{\"event_type\":\"milestone\",\"text\":\"notification.triggering_events_destination\",\"value\":\"DESTINATION_PORT\"},{\"event_type\":\"milestone\",\"text\":\"notification.triggering_events_import_customs_clearance\",\"value\":\"IMPORT_CUSTOMS_CLEARANCE\"},{\"event_type\":\"milestone\",\"text\":\"notification.triggering_events_out_for_delivery\",\"tooltip\":\"notification.triggering_events_out_for_delivery_tooltip\",\"value\":\"OUT_FOR_DELIVERY\"},{\"event_type\":\"milestone\",\"text\":\"notification.triggering_events_customer_delivery\",\"value\":\"CUSTOMER_DELIVERY\"}]}},\"containerLevel\":{\"text\":\"notification.container.choice\",\"tooltip\":\"notification.container.tooltip\",\"fe_type\":\"boolean\",\"value\":false},\"digest\":{\"digest_header\":\"notification.digest_header\",\"digest\":{\"text\":\"notification.digest.all_in_one_mail\",\"fe_type\":\"boolean\",\"value\":false},\"digest_days\":{\"values\":{\"fe_type\":\"multi_choice\",\"from_values\":[{\"text\":\"notification.digest.mondays\",\"value\":\"Mondays\",\"default\":true},{\"text\":\"notification.digest.tuesdays\",\"value\":\"Tuesdays\",\"default\":false},{\"text\":\"notification.digest.wednesdays\",\"value\":\"Wednesdays\",\"default\":false},{\"text\":\"notification.digest.thursdays\",\"value\":\"Thursdays\",\"default\":false},{\"text\":\"notification.digest.fridays\",\"value\":\"Fridays\",\"default\":false},{\"text\":\"notification.digest.saturdays\",\"value\":\"Saturdays\",\"default\":false},{\"text\":\"notification.digest.sundays\",\"value\":\"Sundays\",\"default\":false}]}},\"digest_time\":{\"values\":{\"fe_type\":\"choice\",\"from_values\":[{\"text\":\"00:00\",\"value\":\"00:00\",\"default\":false},{\"text\":\"00:30\",\"value\":\"00:30\",\"default\":false},{\"text\":\"01:00\",\"value\":\"01:00\",\"default\":false},{\"text\":\"01:30\",\"value\":\"01:30\",\"default\":false},{\"text\":\"02:00\",\"value\":\"02:00\",\"default\":false},{\"text\":\"02:30\",\"value\":\"02:30\",\"default\":false},{\"text\":\"03:00\",\"value\":\"03:00\",\"default\":false},{\"text\":\"03:30\",\"value\":\"03:30\",\"default\":false},{\"text\":\"04:00\",\"value\":\"04:00\",\"default\":false},{\"text\":\"04:30\",\"value\":\"04:30\",\"default\":false},{\"text\":\"05:00\",\"value\":\"05:00\",\"default\":false},{\"text\":\"05:30\",\"value\":\"05:30\",\"default\":false},{\"text\":\"06:00\",\"value\":\"06:00\",\"default\":false},{\"text\":\"06:30\",\"value\":\"06:30\",\"default\":false},{\"text\":\"07:00\",\"value\":\"07:00\",\"default\":false},{\"text\":\"07:30\",\"value\":\"07:30\",\"default\":false},{\"text\":\"08:00\",\"value\":\"08:00\",\"default\":true},{\"text\":\"08:30\",\"value\":\"08:30\",\"default\":false},{\"text\":\"09:00\",\"value\":\"09:00\",\"default\":false},{\"text\":\"09:30\",\"value\":\"09:30\",\"default\":false},{\"text\":\"10:00\",\"value\":\"10:00\",\"default\":false},{\"text\":\"10:30\",\"value\":\"10:30\",\"default\":false},{\"text\":\"11:00\",\"value\":\"11:00\",\"default\":false},{\"text\":\"11:30\",\"value\":\"11:30\",\"default\":false},{\"text\":\"12:00\",\"value\":\"12:00\",\"default\":false},{\"text\":\"12:30\",\"value\":\"12:30\",\"default\":false},{\"text\":\"13:00\",\"value\":\"13:00\",\"default\":false},{\"text\":\"13:30\",\"value\":\"13:30\",\"default\":false},{\"text\":\"14:00\",\"value\":\"14:00\",\"default\":false},{\"text\":\"14:30\",\"value\":\"14:30\",\"default\":false},{\"text\":\"15:00\",\"value\":\"15:00\",\"default\":false},{\"text\":\"15:30\",\"value\":\"15:30\",\"default\":false},{\"text\":\"16:00\",\"value\":\"16:00\",\"default\":false},{\"text\":\"16:30\",\"value\":\"16:30\",\"default\":false},{\"text\":\"17:00\",\"value\":\"17:00\",\"default\":false},{\"text\":\"17:30\",\"value\":\"17:30\",\"default\":false},{\"text\":\"18:00\",\"value\":\"18:00\",\"default\":false},{\"text\":\"18:30\",\"value\":\"18:30\",\"default\":false},{\"text\":\"19:00\",\"value\":\"19:00\",\"default\":false},{\"text\":\"19:30\",\"value\":\"19:30\",\"default\":false},{\"text\":\"20:00\",\"value\":\"20:00\",\"default\":false},{\"text\":\"20:30\",\"value\":\"20:30\",\"default\":false},{\"text\":\"21:00\",\"value\":\"21:00\",\"default\":false},{\"text\":\"21:30\",\"value\":\"21:30\",\"default\":false},{\"text\":\"22:00\",\"value\":\"22:00\",\"default\":false},{\"text\":\"22:30\",\"value\":\"22:30\",\"default\":false},{\"text\":\"23:00\",\"value\":\"23:00\",\"default\":false},{\"text\":\"23:30\",\"value\":\"23:30\",\"default\":false}]}}}}", result.getResponse().getContentAsString());

        } catch (Exception ex) {
            fail();
        }

    }

    @Test
    public void testGetNotificationRule() {
        User user = mock(User.class);
        when(user.getId()).thenReturn(USER_ID);
        when(authentication.getUser()).thenReturn(user);

        Long id = initDatabase(false);

        this.mockMvc = MockMvcBuilders.standaloneSetup(notificationsController).build();

        try {
            MvcResult result = this.mockMvc.perform(
                    get("/notifications/rules/" + id)
                            .contentType(MediaType.APPLICATION_JSON)

            ).andReturn();

            assertNotNull(result);

            NotificationRule notificationRule = new ObjectMapper().readValue(result.getResponse().getContentAsString(), NotificationRule.class);
            assertNotNull(notificationRule);
            assertEquals(SUBSCRIPTION_ID, notificationRule.getSubscriptionId());
            assertEquals(NotificationSetting.GENERAL, notificationRule.getSetting());
            assertEquals(NotificationType.FAVORITES, notificationRule.getType());

            assertNotNull(notificationRule.getTradeLanes());
            assertEquals(1, notificationRule.getTradeLanes().size());

            for (TradeLane tradeLane : notificationRule.getTradeLanes()) {
                assertNotNull(tradeLane.getOrigin());
                assertEquals(1, tradeLane.getOrigin().size());
                assertNotNull(tradeLane.getDestination());
                assertEquals(1, tradeLane.getDestination().size());
                assertNotNull(tradeLane.getTransportMode());
                assertEquals(1, tradeLane.getTransportMode().size());

                for (PathPoint origin : tradeLane.getOrigin()) {
                    assertEquals("point-name_destination", origin.getName());
                    assertEquals("code-name_destination", origin.getCode());
                }

                for (PathPoint destination : tradeLane.getDestination()) {
                    assertEquals("point-name", destination.getName());
                    assertEquals("code-name", destination.getCode());
                }

                for (TransportMode transportMode : tradeLane.getTransportMode())
                    assertEquals(TransportMode.AIR, transportMode);
            }

            assertTrue(notificationRule.isActive());
            assertTrue(notificationRule.isContainerLevel());

            for (Event event : notificationRule.getEvents()) {
                assertEquals(Event.CUSTOMER_DELIVERY, event);
            }

            assertFalse(notificationRule.isDigest());
            assertEquals("* * * * * * *", notificationRule.getCronSchedule());
            assertEquals("UTC", notificationRule.getTimezone());
        } catch (Exception ex) {
            fail();
        }

        clearDatabase();
    }

    @Test
    public void testGetAllRules() {
        User user = mock(User.class);
        when(user.getId()).thenReturn(USER_ID);
        when(user.getEmail()).thenReturn(USER_EMAIL);
        when(authentication.getUser()).thenReturn(user);

        UserProfileEntity userProfileEntity = getTestUserProfileEntity();
        userProfileRepository.saveAndFlush(userProfileEntity);

        TagsEntity tagsEntity = new TagsEntity();
        tagsEntity.setTag("Tag");
        tagsEntity.setUuid(CPUUID);
        tagsEntity.setUserProfileEntity(userProfileEntity);

        userTagRepository.saveAndFlush(tagsEntity);

        this.mockMvc = MockMvcBuilders.standaloneSetup(notificationsController).build();

        try {
            MvcResult result = this.mockMvc.perform(
                    get("/notifications/all-rules/" + CPUUID + "?cpCode=" + CPCODE)
                            .contentType(MediaType.APPLICATION_JSON)

            ).andReturn();

            assertNotNull(result);
            assertNotNull(result.getResponse().getContentAsString());
            List allRules = new ObjectMapper().readValue(result.getResponse().getContentAsString(),List.class);
            assertNotNull(allRules);
            assertEquals(1, allRules.size());

            Map data  = (LinkedHashMap)allRules.get(0);
            assertNotNull(data.get("id"));
            assertEquals("12345", data.get("subscriptionId"));
            assertEquals(NotificationSetting.GENERAL.toString(), data.get("setting"));
            assertEquals(NotificationType.FAVORITES.toString(), data.get("type"));
            assertNull(data.get("tradeLanes"));

            assertFalse((Boolean) data.get("active"));
            assertFalse((Boolean) data.get("containerLevel"));
            assertFalse((Boolean) data.get("digest"));

            assertNotNull(data.get("events"));

            List<String> events = (List)data.get("events");

            for(String event : events) {
                assertEquals(Event.STATUS_CHANGED.toString(), event);
            }
            assertNull(data.get("cronSchedule"));
            assertNull(data.get("timezone"));

        } catch (Exception ex) {
            ex.printStackTrace();
            fail();
        }

        clearDatabase();

    }

    @Test
    @Transactional
    public void testCreateNotificationRule() {
        User user = mock(User.class);
        when(user.getId()).thenReturn(USER_ID);
        when(user.getEmail()).thenReturn(USER_EMAIL);
        when(authentication.getUser()).thenReturn(user);

        UserProfileEntity userProfileEntity = getTestUserProfileEntity();
        userProfileRepository.saveAndFlush(userProfileEntity);

        TagsEntity tagsEntity = new TagsEntity();
        tagsEntity.setTag("Tag");
        tagsEntity.setUuid(CPUUID);
        tagsEntity.setUserProfileEntity(userProfileEntity);

        userTagRepository.saveAndFlush(tagsEntity);

        this.mockMvc = MockMvcBuilders.standaloneSetup(notificationsController).build();
        ObjectMapper mapper = new ObjectMapper();

        NotificationRule notificationRule = getTestNotificationRule();
        try {
            MvcResult result = mockMvc.perform(post("/notifications/rules/" + CPUUID + "?cpCode=" + CPCODE).contentType(MediaType.APPLICATION_JSON)
                    .content(mapper.writeValueAsString(notificationRule))).andReturn();

            assertNotNull(result);
            assertNotNull(result.getResponse().getContentAsString());

            NotificationRule saved = mapper.readValue(result.getResponse().getContentAsString(), NotificationRule.class);
            assertNotNull(saved.getId());

            assertEquals("12345", saved.getSubscriptionId());
            assertEquals(NotificationSetting.GENERAL, saved.getSetting());
            assertEquals(NotificationType.FAVORITES, saved.getType());
            assertNull(saved.getTradeLanes());
            assertTrue(saved.isActive());
            assertTrue(saved.isContainerLevel());
            assertNotNull(saved.getEvents());
            assertEquals(1, saved.getEvents().size());

            for (Event event : saved.getEvents()) {
                assertEquals(Event.STATUS_CHANGED, event);
            }

            assertFalse(saved.isDigest());
            assertEquals("* * * * * *", saved.getCronSchedule());
            assertEquals("UTF", saved.getTimezone());

        } catch (Exception ex) {
            fail();
        }

        clearDatabase();

    }

    @Test
    public void testUpdateNotificationRule() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(notificationsController).build();

        User user = mock(User.class);
        when(user.getId()).thenReturn(USER_ID);
        when(user.getEmail()).thenReturn(USER_EMAIL);
        when(authentication.getUser()).thenReturn(user);

        Long id = initDatabase(false);

        NotificationRule notificationRule = getTestNotificationRule();
        notificationRule.setId(id);
        notificationRule.setTimezone("GMC");

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            MvcResult result = this.mockMvc.perform(
                    put("/notifications/rules/" + id)
                            .content(objectMapper.writeValueAsString(notificationRule))
                            .contentType(MediaType.APPLICATION_JSON)

            ).andReturn();

            assertNotNull(result);

            Optional<NotificationRuleEntity> notificationRuleEntity = notificationRuleRepository.findById(id);

            if (!notificationRuleEntity.isPresent()) {
                throw new RuntimeException("Updated rule isnt in database");
            }

            NotificationRuleEntity notificationRuleEntity1 = notificationRuleEntity.get();
            assertEquals("GMC", notificationRuleEntity1.getTimezone());
        } catch (Exception ex) {
            ex.printStackTrace();
            fail();
        }

        clearDatabase();
    }

    @Test
    public void testUpdateNotificationRuleStatus() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(notificationsController).build();

        User user = mock(User.class);
        when(user.getId()).thenReturn(USER_ID);
        when(user.getEmail()).thenReturn(USER_EMAIL);
        when(authentication.getUser()).thenReturn(user);

        Long id = initDatabase(false);

        NotificationRuleStatusChange notificationRuleStatusChange = new NotificationRuleStatusChange();
        notificationRuleStatusChange.setActive(false);

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            MvcResult result = this.mockMvc.perform(
                    patch("/notifications/rules/" + id)
                            .content(objectMapper.writeValueAsString(notificationRuleStatusChange))
                            .contentType(MediaType.APPLICATION_JSON)

            ).andReturn();

            assertNotNull(result);

            Optional<NotificationRuleEntity> notificationRuleEntity = notificationRuleRepository.findById(id);

            if (!notificationRuleEntity.isPresent()) {
                throw new RuntimeException("Updated rule isnt in database");
            }

            NotificationRuleEntity notificationRuleEntity1 = notificationRuleEntity.get();
            assertFalse(notificationRuleEntity1.getActive());
        } catch (Exception ex) {
            fail();
        }

        clearDatabase();
    }

    @Test
    public void testDeleteNotificationRule() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(notificationsController).build();

        User user = mock(User.class);
        when(user.getId()).thenReturn(USER_ID);
        when(user.getEmail()).thenReturn(USER_EMAIL);
        when(authentication.getUser()).thenReturn(user);

        Long id = initDatabase(true);


        try {
            MvcResult result = this.mockMvc.perform(
                    delete("/notifications/rules/" + id)
                            .contentType(MediaType.APPLICATION_JSON)

            ).andReturn();

            assertNotNull(result);

            Optional<NotificationRuleEntity> notificationRuleEntity = notificationRuleRepository.findById(id);

            if (!notificationRuleEntity.isEmpty()) {
                fail();
            }

        } catch (Exception ex) {
            fail();
        }

        clearDatabase();
    }

    private void clearDatabase() {
        userTagRepository.deleteAll();
        notificationConfigRepository.deleteAll();
        userProfileRepository.deleteAll();
        notificationRuleRepository.deleteAll();
    }

    private Long initDatabase(boolean isCustomSettings) {
        UserProfileEntity userProfileEntity = getTestUserProfileEntity();
        userProfileRepository.saveAndFlush(userProfileEntity);

        TagsEntity tagsEntity = new TagsEntity();
        tagsEntity.setTag("Tag");
        tagsEntity.setUuid(CPUUID);
        tagsEntity.setUserProfileEntity(userProfileEntity);

        userTagRepository.saveAndFlush(tagsEntity);

        NotificationConfigEntity notificationConfigEntity = getTestNotificationConfigEntity();
        notificationConfigEntity.setUserProfileEntity(userProfileEntity);
        notificationConfigRepository.saveAndFlush(notificationConfigEntity);

        NotificationRuleEntity notificationRuleEntity = getTestNotificationRuleEntity();
        notificationRuleEntity.setNotificationConfigEntity(notificationConfigEntity);

        if(isCustomSettings) {
            notificationRuleEntity.setSetting(NotificationSetting.CUSTOM);
        }

        notificationRuleRepository.saveAndFlush(notificationRuleEntity);

        return notificationRuleEntity.getId();
    }

}

我不知道这可能是一个问题。我检查它与另一个项目,它似乎是相同的配置.是不是jenkins服务器上的防火墙有问题?但也许不会,因为另一个测试运行顺利。谢谢你的帮助。

xjreopfe

xjreopfe1#

您正在尝试在特权端口上运行,即。一个是< 1024的数字。
默认情况下,操作系统将阻止此操作,除非您以root身份运行。
将端口号设置为大于1024的值应该可以解决此问题。

相关问题