CarDataApiControllerTest.java 6.01 KB
package com.bs.cardata.controller;

import com.bs.cardata.BsApplication;
import com.bs.cardata.constant.ServiceConstants;
import com.bs.common.core.redis.RedisService;
import com.bs.common.utils.sign.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

import java.util.UUID;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * CarDataApiController clearCache 接口测试
 */
@Slf4j
@SpringBootTest(classes = BsApplication.class, properties = "spring.application.name=bs-car-data")
@AutoConfigureMockMvc
@ActiveProfiles("local")
public class CarDataApiControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private RedisService redisService;

    /**
     * 生成合法加密参数
     */
    private String[] generateValidParams() {
        String nonce = UUID.randomUUID().toString();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String plainText = nonce + timestamp + ServiceConstants.CLEAR_CACHE_SECRET;
        String token = Md5Utils.getMD532Str(plainText);
        return new String[]{token, timestamp, nonce};
    }

    /**
     * 测试正常清除缓存
     */
    @Test
    public void testClearCache_success() throws Exception {
        String[] params = generateValidParams();

        mockMvc.perform(get("/common/api/clearCache")
                        .param("token", params[0])
                        .param("timestamp", params[1])
                        .param("nonce", params[2]))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.msg").value("缓存清除成功"));

        log.info("testClearCache_success 通过");
    }

    /**
     * 测试时间戳格式错误
     */
    @Test
    public void testClearCache_invalidTimestamp() throws Exception {
        String nonce = UUID.randomUUID().toString();
        String token = Md5Utils.getMD532Str(nonce + "abc" + ServiceConstants.CLEAR_CACHE_SECRET);

        mockMvc.perform(get("/common/api/clearCache")
                        .param("token", token)
                        .param("timestamp", "abc")
                        .param("nonce", nonce))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.msg").value("时间戳格式不正确"));

        log.info("testClearCache_invalidTimestamp 通过");
    }

    /**
     * 测试时间戳过期(超出5分钟窗口)
     */
    @Test
    public void testClearCache_expiredTimestamp() throws Exception {
        String nonce = UUID.randomUUID().toString();
        // 构造一个6分钟前的时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() - 6 * 60 * 1000L);
        String plainText = nonce + timestamp + ServiceConstants.CLEAR_CACHE_SECRET;
        String token = Md5Utils.getMD532Str(plainText);

        mockMvc.perform(get("/common/api/clearCache")
                        .param("token", token)
                        .param("timestamp", timestamp)
                        .param("nonce", nonce))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.msg").value("请求已过期,时间戳超出有效窗口"));

        log.info("testClearCache_expiredTimestamp 通过");
    }

    /**
     * 测试签名校验失败(错误的token)
     */
    @Test
    public void testClearCache_invalidToken() throws Exception {
        String nonce = UUID.randomUUID().toString();
        String timestamp = String.valueOf(System.currentTimeMillis());

        mockMvc.perform(get("/common/api/clearCache")
                        .param("token", "invalid_token_123456")
                        .param("timestamp", timestamp)
                        .param("nonce", nonce))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.msg").value("加密参数校验失败"));

        log.info("testClearCache_invalidToken 通过");
    }

    /**
     * 测试加密参数只能使用一次(重放攻击)
     */
    @Test
    public void testClearCache_nonceReuse() throws Exception {
        String[] params = generateValidParams();

        // 第一次调用:应成功
        mockMvc.perform(get("/common/api/clearCache")
                        .param("token", params[0])
                        .param("timestamp", params[1])
                        .param("nonce", params[2]))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));

        // 第二次使用相同参数:应被拒绝
        mockMvc.perform(get("/common/api/clearCache")
                        .param("token", params[0])
                        .param("timestamp", params[1])
                        .param("nonce", params[2]))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.msg").value("该加密参数已被使用,请重新生成"));

        log.info("testClearCache_nonceReuse 通过");
    }

    /**
     * 测试缺少必要参数
     */
    @Test
    public void testClearCache_missingParams() throws Exception {
        mockMvc.perform(get("/common/api/clearCache"))
                .andDo(print())
                .andExpect(status().isBadRequest());

        log.info("testClearCache_missingParams 通过");
    }
}