Skip to content

Commit

Permalink
[Improve] add push module controller unit test (#2451)
Browse files Browse the repository at this point in the history
Signed-off-by: yuluo-yx <yuluo08290126@gmail.com>
Signed-off-by: YuLuo <yuluo08290126@gmail.com>
yuluo-yx authored Aug 6, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 58e6e1a commit e9da2d2
Showing 3 changed files with 210 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -18,7 +18,6 @@
package org.apache.hertzbeat.alert.reduce;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -84,37 +83,43 @@ public boolean filterSilence(Alert alert) {
}
}
if (match) {
LocalDateTime nowDate = LocalDateTime.now();
if (alertSilence.getType() == 0) {
// once time
boolean startMatch = alertSilence.getPeriodStart() == null || nowDate.isAfter(alertSilence.getPeriodStart().toLocalDateTime());
boolean endMatch = alertSilence.getPeriodEnd() == null || nowDate.isBefore(alertSilence.getPeriodEnd().toLocalDateTime());
if (startMatch && endMatch) {
int times = Optional.ofNullable(alertSilence.getTimes()).orElse(0);
alertSilence.setTimes(times + 1);
alertSilenceDao.save(alertSilence);
return false;
}
return checkAndSave(LocalDateTime.now(), alertSilence);
} else if (alertSilence.getType() == 1) {
// cyc time
int currentDayOfWeek = nowDate.toLocalDate().getDayOfWeek().getValue();
int currentDayOfWeek = LocalDateTime.now().toLocalDate().getDayOfWeek().getValue();
if (alertSilence.getDays() != null && !alertSilence.getDays().isEmpty()) {
boolean dayMatch = alertSilence.getDays().stream().anyMatch(item -> item == currentDayOfWeek);
if (dayMatch) {
LocalTime nowTime = nowDate.toLocalTime();
boolean startMatch = alertSilence.getPeriodStart() == null || nowTime.isAfter(alertSilence.getPeriodStart().toLocalTime());
boolean endMatch = alertSilence.getPeriodEnd() == null || nowTime.isBefore(alertSilence.getPeriodEnd().toLocalTime());
if (startMatch && endMatch) {
int times = Optional.ofNullable(alertSilence.getTimes()).orElse(0);
alertSilence.setTimes(times + 1);
alertSilenceDao.save(alertSilence);
return false;
}
return checkAndSave(LocalDateTime.now(), alertSilence);
}
}
}
}
}
return true;
}

/**
* Check AlertSilence start and end match, to save alertSilence obj.
* @param times LocalDateTime.
* @param alertSilence {@link AlertSilence}
* @return boolean
*/
private boolean checkAndSave(LocalDateTime times, AlertSilence alertSilence) {

boolean startMatch = alertSilence.getPeriodStart() == null || times.isAfter(alertSilence.getPeriodStart().toLocalDateTime());
boolean endMatch = alertSilence.getPeriodEnd() == null || times.isBefore(alertSilence.getPeriodEnd().toLocalDateTime());

if (startMatch && endMatch) {

int time = Optional.ofNullable(alertSilence.getTimes()).orElse(0);
alertSilence.setTimes(time + 1);
alertSilenceDao.save(alertSilence);
return false;
}

return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.hertzbeat.push.controller;

import org.apache.hertzbeat.common.constants.CommonConstants;
import org.apache.hertzbeat.common.entity.push.PushMetricsDto;
import org.apache.hertzbeat.common.util.JsonUtil;
import org.apache.hertzbeat.push.service.PushService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

/**
* test case for {@link PushController}
*/

@ExtendWith(MockitoExtension.class)
class PushControllerTest {

private MockMvc mockMvc;

@Mock
private PushService pushService;

@InjectMocks
private PushController pushController;

private PushMetricsDto mockPushMetricsDto;

@BeforeEach
void setUp() {

this.mockMvc = standaloneSetup(this.pushController).build();

mockPushMetricsDto = PushMetricsDto.builder().build();
}

@Test
void testPushMetrics() throws Exception {

this.mockMvc.perform(MockMvcRequestBuilders.post("/api/push")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.toJson(mockPushMetricsDto)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE))
.andReturn();
}

@Test
void testGetMetrics() throws Exception {

Long id = 6565463543L;
Long time = 6565463543L;

when(pushService.getPushMetricData(id, time)).thenReturn(mockPushMetricsDto);

this.mockMvc.perform(MockMvcRequestBuilders.get("/api/push")
.contentType(MediaType.APPLICATION_JSON)
.param("id", id.toString())
.param("time", time.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE))
.andReturn();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.hertzbeat.push.controller;

import java.io.InputStream;
import org.apache.hertzbeat.common.constants.CommonConstants;
import org.apache.hertzbeat.push.service.PushGatewayService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* test case for {@link PushGatewayController}
*/

@ExtendWith(MockitoExtension.class)
class PushGatewayControllerTest {

private MockMvc mockMvc;

@Mock
private PushGatewayService pushGatewayService;

@InjectMocks
private PushGatewayController gatewayController;

@BeforeEach
void setUp() {

mockMvc = MockMvcBuilders.standaloneSetup(gatewayController).build();
}

@Test
void testPushMetricsSuccess() throws Exception {

String mockData = "some metric data";

when(pushGatewayService.pushMetricsData(any(InputStream.class))).thenReturn(true);

mockMvc.perform(post("/api/push/pushgateway")
.contentType(MediaType.APPLICATION_JSON)
.content(mockData))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value((int) CommonConstants.SUCCESS_CODE))
.andExpect(jsonPath("$.msg").value("Push success"));
}

@Test
void testPushMetricsFailure() throws Exception {

String mockData = "some metric data";

when(pushGatewayService.pushMetricsData(any(InputStream.class))).thenReturn(false);

mockMvc.perform(post("/api/push/pushgateway")
.contentType(MediaType.APPLICATION_JSON)
.content(mockData))
.andExpect(status().isOk())
.andExpect(jsonPath("$.msg").value("Push failed"));
}

}

0 comments on commit e9da2d2

Please sign in to comment.