test(后端切片): 不连库的 @SpringBootTest 装配切片,把 §2 那个 "0 例进容器" 变成 1

四面 9 分任务书 §2 后端一行的实测是「@Test 4035、@SpringBootTest=0、@MockBean=0」——
纯 mock 写法证不到两件版本硬地板的前提:properties 里的 aiimage.client-version.* 能不能
绑进闸门(@Value),以及闸门作为 bean 会不会真被挂进 servlet 过滤器链。任一件坏掉,
4,035 例照样全绿,现网是"闸门写了但没生效"。

本支切片把这两件事变成实跑判据:真容器 + MockMvc + 真实的 SecurityConfig 一起装,
不扫描业务包、不加载 DataSource/MyBatis/Redis/RocketMQ,所以本机无 Docker/无 MySQL
也能跑(任务书要的正是这个形状,真库用例一条都没写进来)。

踩到并写进注释的一个形状坑:一开始没装 SecurityConfig,切片落到 Boot 默认安全规则上,
POST 被 CSRF 打成 403、GET 被匿名打成 401,闸门根本没执行机会——那种红绿都不说明任何事。
现网是 csrf disable + anyRequest permitAll,闸门 @Order(LOWEST_PRECEDENCE) 排在它之后,
所以必须带上真实那一层,切片跑的才是同一条链。

实跑:mvn -o test -Dtest=ClientVersionGuardContextSliceTest ⇒ Tests run: 6, Failures: 0,
Errors: 0(本机 Java 21,无 Docker)。

变异自证(三刀,逐轮还原后 sha8=763e30cd 与原始字节相等并复跑 6/0/0):
  地板 4.0.40→4.0.1        ⇒ 1 例红(@Value 确实在从 properties 取值)
  @Import 摘掉闸门          ⇒ 2 failures + 1 error(闸门确实是容器里的,不是测试 new 的)
  enforce=true→false       ⇒ 2 例红(记账档与拒绝档真由属性决定)
没有这三刀,"6 例绿"和"6 例恒绿"是同一个读数。

覆盖面如实收窄:这一支只守版本闸门一例装配,鉴权拦截器/幂等闸门还没进容器,
不是"容器化已铺开"。本文件是纯测试,现网行为零变更。
This commit is contained in:
2026-10-08 23:53:10 +08:00
parent 15e0451191
commit 4e154e5318
@@ -0,0 +1,163 @@
package com.nanri.aiimage.config;
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.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.DisplayName;
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.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
/**
* 上下文装配切片(四面 9 分口径 §2 后端「4035 例全在 mock 边界内」那一格的补法)。
*
* <p>为什么专门开这一支:本仓 4,035 个 {@code @Test} 全部在 mock 边界内跑——对象是 new 出来的、
* {@code @Value} 是 ReflectionTestUtils 注进去的。那种写法证不了两件事,而这两件事恰好是
* 版本硬地板能不能生效的前提:① 属性文件里的 {@code aiimage.client-version.*} 能不能绑进闸门;
* ② 闸门作为 bean 注册后,Spring Boot 会不会真的把它挂进 servlet 过滤器链、顺序对不对。
* 上面任何一件坏掉,纯 mock 用例照样全绿,现网则是"闸门写了但没生效"。
*
* <p>不连库:上下文里只有 MVC 与这一个闸门({@code SliceConfig} 手工装配,不扫描业务包、
* 不加载 DataSource/MyBatis/Redis/RocketMQ),所以本机没有 Docker、没有 MySQL 也能跑
* ——这正是任务书要求的形状("真库用例显式标注仅 CI/远端可跑,不许在本机做成恒绿闸门")。
*
* <p>跑法:{@code mvn -o test -Dtest=ClientVersionGuardContextSliceTest}(cwd = backend-java)。
*
* <p>真实的 SecurityConfig 也装进切片,而不是把它排除掉:现网里 CSRF 已关闭、路径全部 permitAll,安全链从不拦住客户端请求,而闸门是 {@code @Order(LOWEST_PRECEDENCE)},排在它<b>之后</b>。带上这一层,本切片跑的就是现网同一条过滤器链;换成 Boot 默认规则时 POST 被 CSRF 打成 403、GET 被匿名访问打成 401,闸门根本没机会执行——那种红与绿都不说明任何事。
*/
@SpringBootTest(
classes = ClientVersionGuardContextSliceTest.SliceConfig.class,
webEnvironment = SpringBootTest.WebEnvironment.MOCK,
properties = {
"aiimage.client-version.min-supported-version=4.0.40",
"aiimage.client-version.enforce=true",
})
@AutoConfigureMockMvc
class ClientVersionGuardContextSliceTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
/** 只装 MVC + 被测闸门;被 @Import 的 PingController 提供一条客户端路径与一条非客户端路径。 */
@Configuration(proxyBeanMethods = false)
@EnableWebMvc
@Import({ClientVersionGuardFilter.class, SecurityConfig.class,
SlicePingController.class, JacksonAutoConfiguration.class})
static class SliceConfig {
}
@RestController
static class SlicePingController {
@PostMapping("/api/client/ping")
String clientPing(@RequestBody(required = false) String body,
@RequestHeader(value = "X-Client-Version", required = false) String version) {
return "PONG:" + (version == null ? "-" : version);
}
@GetMapping("/api/admin/users")
String adminPath() {
return "ADMIN";
}
}
@Test
@DisplayName("闸门确实在容器里,且是 Spring 建的 bean(不是测试 new 出来的)")
void filterIsAContainerBean() {
ClientVersionGuardFilter filter = context.getBean(ClientVersionGuardFilter.class);
assertNotNull(filter, "闸门没进容器 ⇒ 下面三条断言全部失去意义");
}
@Test
@DisplayName("properties 里的地板值真被 @Value 绑定(纯 mock 用例证不到这一层)")
void floorComesFromProperties() throws Exception {
// 4.0.10 < 4.0.40:若属性没绑进闸门,minSupportedVersion 会是空串 ⇒ 闸门不配置 ⇒ 放行到 controller
MvcResult result = mockMvc.perform(post("/api/client/ping")
.contentType(MediaType.APPLICATION_JSON)
.header("X-Client-Version", "4.0.10")
.content("{}"))
.andExpect(status().isOk())
.andReturn();
String body = result.getResponse().getContentAsString();
assertFalse(body.startsWith("PONG"),
"低版本客户端被放行了 ⇒ properties 没绑进闸门,或闸门不在过滤器链里:body=" + body);
assertTrue(body.contains("4012"),
"拒绝码不是 4012,本切片的判据与闸门实现脱节:" + body);
}
@Test
@DisplayName("版本达标时过滤器放行,请求真的走到 controller")
void allowedVersionReachesController() throws Exception {
mockMvc.perform(post("/api/client/ping")
.contentType(MediaType.APPLICATION_JSON)
.header("X-Client-Version", "4.0.46")
.content("{}"))
.andExpect(status().isOk())
.andExpect(content().string("PONG:4.0.46"));
}
@Test
@DisplayName("未上报版本默认不拒(存量装机不受影响),仍走到 controller")
void unreportedIsSparedByDefault() throws Exception {
mockMvc.perform(post("/api/client/ping").contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(status().isOk())
.andExpect(content().string("PONG:-"));
}
@Test
@DisplayName("非客户端路径不参与判定(后台与内部令牌通道零影响)")
void nonClientPathUntouched() throws Exception {
mockMvc.perform(get("/api/admin/users").header("X-Client-Version", "0.0.1"))
.andExpect(status().isOk())
.andExpect(content().string("ADMIN"));
}
@Test
@DisplayName("拒绝形态是 200 + success=false + code 4012(与全仓业务拒绝口径一致)")
void rejectionKeepsAppConvention() throws Exception {
MvcResult result = mockMvc.perform(post("/api/client/ping")
.contentType(MediaType.APPLICATION_JSON)
.header("X-Client-Version", "3.9.9")
.content("{}"))
.andExpect(status().isOk())
.andReturn();
String body = result.getResponse().getContentAsString();
assertEquals(Boolean.FALSE, parseSuccess(body), "业务拒绝必须写 success=false:" + body);
assertTrue(body.contains("minSupportedVersion"),
"响应体没带 minSupportedVersion,前端就无从提示升级:" + body);
}
/** 用字符串而不是 ObjectMapper:这条用例只关心形状,不想再引一层依赖。 */
private static Boolean parseSuccess(String body) {
int idx = body.indexOf("\"success\"");
if (idx < 0) {
return null;
}
String tail = body.substring(idx).replace(" ", "");
return tail.startsWith("\"success\":false") ? Boolean.FALSE : Boolean.TRUE;
}
}