test: 거짓 통과·흔들림·저장소 읽기 경로를 막도록 시험을 고친다

문제:
- GraphQlDeploymentModeRegistryParityTest가 태그 없이 test에서
  docs/registries/env-keys.yaml을 읽었다. 입력을 선언하지 않아 test 캐시가
  registry 변경을 놓쳤고, modules.json을 거슬러 올라가 저장소 루트 가드를
  우회했다(build-logic/AGENTS.md 「저장소 파일을 읽는 테스트」).
- 「값을 싣지 않는다」 단언 넷(WebSecurityContextBridgeTest, scalar 둘)이 예외
  타입을 보지 않아, 메시지 null인 NPE로 바꿔도 통과했다.
- FileserverAdminControllerRequestBodyValidationTest는 @RequestBody가 하나도 없는
  controller에도 통과했다.
- GraphQlRequestDeadlineTest가 sleep(500) 뒤에 하위 필드 부재를 단언했다. 부하에
  따라 기다림이 짧으면 거짓 통과다.
- 두 동작을 한 시험에서 보던 셋(표 입력 반복문, when 둘).

고친 것:
- registry 대조 시험에 document-contract 태그를 달고 graphql leaf에
  mainStage lane graphqlDocumentContractTest를 둔다(lane은 다음 커밋의
  build.gradle에 있다. 그 파일의 다른 변경과 같이 간다).
- 부재 단언에 예외 타입(CoercingParseValueException,
  UntrustedTenantInputException)을 먼저 둔다.
- admin 시험은 @RequestBody 매개변수 목록을 고정한 뒤 @Valid를 본다.
- deadline 시험은 slowNode 실행이 끝났다는 신호(Instrumentation
  beginExecution 완료, 세대 번호로 이전 시험의 늦은 완료를 거른다)를 기다린 뒤
  부재를 본다.
- 표 입력(scalar 넷의 부재 단언 포함)은 @ParameterizedTest로, 두 동작은 시험 둘로
  나눴다. 고친 시험은 GWT와 catchThrowable로 when을 하나로 둔다.
- decisions 2.1에 「시험 형식 일괄 전환 안 함」(리뷰 README 6절 ④) 행을 더했다.

Refs: RR9-03-17, RR9-03-18, RR9-03-19, RR9-03-20, RR9-03-22
This commit is contained in:
DongHyeonka
2026-11-13 06:34:32 +09:00
parent fe0f8141ec
commit 1185b36a6d
10 changed files with 172 additions and 29 deletions
+1
View File
@@ -58,6 +58,7 @@
| 개선 매뉴얼을 먼저(지난 것) | 다음 개선 작업 전에 repo마다 개선 매뉴얼을 만든다 → 2026-11-06 「매뉴얼 체계」로 바뀜 | 소유자 | 2026-11-05 | 2026-11-05 총괄 세션 brief |
| 스킬 | 리뷰·수정에 알맞은 스킬을 쓴다 | 소유자 | 2026-11-05 | `1103` 2절 |
| `@DisplayName` 언어 | 한국어(기본값 영어를 거부) | 소유자 | 2026-09-25 | 결정 5, `.claude/rules/java-tests.md` 규칙 2 |
| 시험 형식 일괄 전환 | 영어 `@DisplayName`과 `// when` 없는 시험을 한꺼번에 바꾸지 않는다. 규칙(`.claude/rules/java-tests.md`)은 그대로이고, 고치는 시험에 적용한다. 한꺼번에 바꾸면 수천 줄의 diff가 결함 수정을 가린다 | 기본값(소유자가 뒤집을 수 있다) | 2026-11-12 | 2026-11-12 전체 리뷰 기록 README 6절 ④ |
| 학습 문서(지난 것) | 삭제된 코드를 설명하는 학습 문서(지금 `docs/history/study/*.ko.md`, `docs/history/packages/*-superpowers-package/`)는 현재 코드에 맞게 갱신 → 2026-11-07 갱신하지 않고 기록으로 보관(머리 블록만 단다)으로 바뀜 | 소유자 | 2026-09-25 | 결정 6, design-docs `repo-structure/README.md` 3.2절 |
| 문서 체계 | 문서를 수명으로 나눈다. 살아 있는 문서는 제자리에 두고 한국어로 옮긴다. 기록은 `docs/history/`, 설계서는 `docs/design/`, 결정 기록은 `docs/adr/`에 둔다. 폴더 이름은 짝 프론트와 같이 쓴다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절, 적용은 `docs/README.md` |
| 한국어의 범위 | 살아 있는 문서는 본문까지 한국어로 쓴다. 기록 문서는 맨 위에 한국어 머리 블록(상태·작성일·요약·현재 정본)을 달고 본문은 원문 그대로 둔다. 상태는 한국어 고정 어휘다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절 |
@@ -98,8 +98,9 @@ class GraphQlRequestDeadlineTest {
assertThat(finished)
.as("the running resolver is not interrupted; it finishes on its own thread")
.isTrue();
// Room for graphql-java to have dispatched the child, had the cancellation not stopped it.
Thread.sleep(500);
assertThat(SlowWork.slowExecutionEnded.await(5, TimeUnit.SECONDS))
.as("the execution ends after its last field, so a child that was going to start has")
.isTrue();
assertThat(SlowWork.DETAIL_INVOCATIONS)
.as("a cancelled execution must not start new fields once the client has been answered")
.hasValue(0);
@@ -114,5 +115,10 @@ class GraphQlRequestDeadlineTest {
GraphQlClientPolicy shortBudgetClientPolicy() {
return RuntimeLimitsTestSupport.policyWithExecutionBudget(BUDGET);
}
@Bean
graphql.execution.instrumentation.Instrumentation slowExecutionEndSignal() {
return SlowWork.executionEndSignal();
}
}
}
@@ -2,6 +2,13 @@ package dev.caskeleton.adapter.inbound.graphql.runtime;
import dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import graphql.ExecutionResult;
import graphql.execution.instrumentation.Instrumentation;
import graphql.execution.instrumentation.InstrumentationContext;
import graphql.execution.instrumentation.InstrumentationState;
import graphql.execution.instrumentation.SimpleInstrumentationContext;
import graphql.execution.instrumentation.SimplePerformantInstrumentation;
import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
@@ -85,12 +92,43 @@ final class RuntimeLimitsTestSupport {
static final AtomicInteger DETAIL_INVOCATIONS = new AtomicInteger();
static volatile CountDownLatch slowFinished = new CountDownLatch(1);
/**
* Counted down when a {@code slowNode} execution begun after the last {@link #reset()} has
* ended. The point after which a child field can no longer start, so an absence asserted after
* it is an absence and not a guess at how long the engine needs.
*/
static volatile CountDownLatch slowExecutionEnded = new CountDownLatch(1);
private static final AtomicInteger GENERATION = new AtomicInteger();
private SlowWork() {}
static void reset() {
SLOW_STARTED.set(0);
DETAIL_INVOCATIONS.set(0);
slowFinished = new CountDownLatch(1);
slowExecutionEnded = new CountDownLatch(1);
GENERATION.incrementAndGet();
}
/** Signals the end of each {@code slowNode} execution begun in the current generation. */
static Instrumentation executionEndSignal() {
return new SimplePerformantInstrumentation() {
@Override
public InstrumentationContext<ExecutionResult> beginExecution(
InstrumentationExecutionParameters parameters, InstrumentationState state) {
int generation = GENERATION.get();
CountDownLatch ended = slowExecutionEnded;
boolean slow =
parameters.getQuery() != null && parameters.getQuery().contains("slowNode");
return SimpleInstrumentationContext.whenCompleted(
(result, failure) -> {
if (slow && generation == GENERATION.get()) {
ended.countDown();
}
});
}
};
}
}
@@ -8,6 +8,8 @@ import java.nio.file.Path;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -16,7 +18,11 @@ import org.junit.jupiter.api.Test;
* <p>A mode the registry documents but the enum cannot bind fails at startup with a type-conversion
* error; a mode the enum has but the registry omits is one no operator is told about. Which runtime
* accepts each mode is held by {@code GraphQlDeploymentModeContractTest}.
*
* <p>Tagged {@code document-contract}: it reads a repository document, so it runs in the leaf's
* main-stage lane {@code graphqlDocumentContractTest}, never in the cached {@code test}.
*/
@Tag("document-contract")
class GraphQlDeploymentModeRegistryParityTest {
private static final Pattern ALLOWED_VALUES =
@@ -24,11 +30,16 @@ class GraphQlDeploymentModeRegistryParityTest {
"name: APP_GRAPHQL_DEPLOYMENT_MODE.*?allowed_values: \\[([^\\]]*)\\]", Pattern.DOTALL);
@Test
@DisplayName("registry의 APP_GRAPHQL_DEPLOYMENT_MODE 허용 값은 enum이 받는 값과 정확히 같다")
void theRegistryListsExactlyTheModesTheEnumHas() throws IOException {
// given
String registry = Files.readString(repositoryRoot().resolve("docs/registries/env-keys.yaml"));
Matcher matcher = ALLOWED_VALUES.matcher(registry);
assertThat(matcher.find()).isTrue();
// when
Matcher matcher = ALLOWED_VALUES.matcher(registry);
// then
assertThat(matcher.find()).as("the registry row and its allowed_values").isTrue();
assertThat(Arrays.stream(matcher.group(1).split(",")).map(String::trim))
.as("the registry is what an operator sets APP_GRAPHQL_DEPLOYMENT_MODE from")
.containsExactlyInAnyOrderElementsOf(
@@ -41,9 +41,13 @@ class GraphQlMutationResultMapperTest {
}
@Test
void oneRootFieldCallsOneUseCase() {
void oneRootFieldThatCallsOneUseCaseIsAccepted() {
assertThatCode(() -> GraphQlMutationContractValidator.requireSingleUseCase(CREATE_ORDER, 1))
.doesNotThrowAnyException();
}
@Test
void oneRootFieldThatCallsTwoUseCasesIsRefused() {
assertThatThrownBy(() -> GraphQlMutationContractValidator.requireSingleUseCase(CREATE_ORDER, 2))
.isInstanceOf(GraphQlMutationContractException.class)
.hasMessageContaining("one use case");
@@ -58,6 +62,13 @@ class GraphQlMutationResultMapperTest {
() -> GraphQlMutationContractValidator.rejectRequestWideTransaction(roots, true))
.isInstanceOf(GraphQlMutationContractException.class)
.hasMessageContaining("not a shared transaction");
}
@Test
void severalRootMutationsWithoutARequestWideTransactionAreAccepted() {
List<GraphQlMutationCoordinate> roots =
List.of(CREATE_ORDER, new GraphQlMutationCoordinate("Mutation.createInvoice"));
assertThatCode(
() -> GraphQlMutationContractValidator.rejectRequestWideTransaction(roots, false))
.doesNotThrowAnyException();
@@ -232,6 +232,10 @@ class HmacGraphQlCursorCodecTest {
void framingRejectsADeclaredLengthLongerThanTheBody() {
assertThatThrownBy(() -> GraphQlCursorFraming.readAll("99:short"))
.isInstanceOf(GraphQlCursorException.class);
}
@Test
void framingAcceptsADeclaredLengthThatMatchesTheBody() {
assertThatCode(() -> GraphQlCursorFraming.readAll("5:hello")).doesNotThrowAnyException();
}
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.graphql.scalar;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarDefinition;
import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarManifest;
@@ -13,7 +14,13 @@ import java.time.Instant;
import java.time.LocalDate;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/** Stable custom scalar serialization and coercion contract (Stable plan Task 13). */
class GraphQlScalarContractTest {
@@ -79,14 +86,30 @@ class GraphQlScalarContractTest {
assertThat(LongScalar.serialize(42L)).isEqualTo("42");
}
@Test
void coercionErrorsDoNotEchoTheOffendingValue() {
static Stream<Arguments> parsers() {
return Stream.of(
Arguments.of("UUID", (Function<String, Object>) UuidScalar::parse),
Arguments.of("Date", (Function<String, Object>) DateScalar::parse),
Arguments.of("BigDecimal", (Function<String, Object>) BigDecimalScalar::parse),
Arguments.of("Long", (Function<String, Object>) LongScalar::parse));
}
@ParameterizedTest(name = "{0}")
@MethodSource("parsers")
@DisplayName("scalar 변환 오류는 거절한 값을 메시지에 싣지 않는다")
void coercionErrorsDoNotEchoTheOffendingValue(String scalar, Function<String, Object> parse) {
// given
String secret = "4111-1111-1111-1111";
assertThatThrownBy(() -> UuidScalar.parse(secret)).hasMessageNotContaining(secret);
assertThatThrownBy(() -> DateScalar.parse(secret)).hasMessageNotContaining(secret);
assertThatThrownBy(() -> BigDecimalScalar.parse(secret)).hasMessageNotContaining(secret);
assertThatThrownBy(() -> LongScalar.parse(secret)).hasMessageNotContaining(secret);
// when
Throwable refused = catchThrowable(() -> parse.apply(secret));
// then
// The type first: a message that merely lacks the value also passes for an NPE thrown before
// the scalar ever looked at it, which is not the refusal this test is about.
assertThat(refused)
.isInstanceOf(CoercingParseValueException.class)
.hasMessageNotContaining(secret);
}
@Test
@@ -81,6 +81,7 @@ class GraphQlScalarSymmetryTest {
String secret = "9".repeat(500);
assertThatThrownBy(() -> BigDecimalScalar.parse(secret))
.isInstanceOf(graphql.schema.CoercingParseValueException.class)
.hasMessageNotContaining(secret)
.hasMessageNotContaining("999");
}
@@ -1,13 +1,15 @@
package dev.caskeleton.adapter.inbound.web.advanced.security;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* A tenant a caller chose is a cross-tenant read waiting to happen.
@@ -40,22 +42,51 @@ class WebSecurityContextBridgeTest {
assertThatThrownBy(
() ->
bridge.resolve(AuthenticationView.anonymous(), Map.of("tenant", "tenant-attacker")))
.isInstanceOf(UntrustedTenantInputException.class)
.hasMessageNotContaining("tenant-attacker");
}
@Test
@DisplayName("every spelling of a tenant input is refused")
void everySpellingOfATenantInputIsRefused() {
@ParameterizedTest(name = "{0}")
@ValueSource(strings = {"X-Tenant-Id", "tenant-id", "TenantId", "TENANT"})
@DisplayName("tenant 입력은 어떤 철자로 와도 거절된다")
void everySpellingOfATenantInputIsRefused(String name) {
// given
WebTenantContextResolver resolver = new WebTenantContextResolver();
for (String name : new String[] {"X-Tenant-Id", "tenant-id", "TenantId", "TENANT"}) {
assertThatThrownBy(() -> resolver.rejectTenantInput(Map.of(name, "t")))
.as("a case or hyphen variant is the same header to a proxy")
.isInstanceOf(UntrustedTenantInputException.class);
}
assertThatCode(() -> resolver.rejectTenantInput(Map.of("Accept", "application/json")))
.doesNotThrowAnyException();
assertThatCode(() -> resolver.rejectTenantInput(null)).doesNotThrowAnyException();
// when
Throwable refused = catchThrowable(() -> resolver.rejectTenantInput(Map.of(name, "t")));
// then
assertThat(refused)
.as("a case or hyphen variant is the same header to a proxy")
.isInstanceOf(UntrustedTenantInputException.class);
}
@Test
@DisplayName("tenant가 아닌 입력은 거절되지 않는다")
void anInputThatNamesNoTenantIsNotRefused() {
// given
WebTenantContextResolver resolver = new WebTenantContextResolver();
// when
Throwable refused =
catchThrowable(() -> resolver.rejectTenantInput(Map.of("Accept", "application/json")));
// then
assertThat(refused).isNull();
}
@Test
@DisplayName("입력이 없으면 거절되지 않는다")
void noInputIsNotRefused() {
// given
WebTenantContextResolver resolver = new WebTenantContextResolver();
// when
Throwable refused = catchThrowable(() -> resolver.rejectTenantInput(null));
// then
assertThat(refused).isNull();
}
@Test
@@ -7,12 +7,12 @@ import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.RequestBody;
/**
* W4 red team BE-INPUT-002 — every {@code @RequestBody} on the admin controller must also carry
* {@code @Valid}.
* Every {@code @RequestBody} on the admin controller must also carry {@code @Valid}.
*
* <p>{@code reconcileOrphans} shipped a {@code @RequestBody} without {@code @Valid}, unlike every
* sibling handler (relocate/force-delete/…). Harmless today because {@code
@@ -24,20 +24,37 @@ import org.springframework.web.bind.annotation.RequestBody;
class FileserverAdminControllerRequestBodyValidationTest {
@Test
@DisplayName("admin controller의 @RequestBody 매개변수는 모두 @Valid를 함께 단다")
void everyRequestBodyParameterAlsoCarriesValid() {
// given
List<String> bodies = new ArrayList<>();
List<String> offenders = new ArrayList<>();
// when
for (Method method : FileserverAdminController.class.getDeclaredMethods()) {
for (Parameter parameter : method.getParameters()) {
if (parameter.isAnnotationPresent(RequestBody.class)
&& !parameter.isAnnotationPresent(Valid.class)) {
offenders.add(method.getName() + "(" + parameter.getType().getSimpleName() + ")");
if (!parameter.isAnnotationPresent(RequestBody.class)) {
continue;
}
String handler = method.getName() + "(" + parameter.getType().getSimpleName() + ")";
bodies.add(handler);
if (!parameter.isAnnotationPresent(Valid.class)) {
offenders.add(handler);
}
}
}
// then
assertThat(bodies)
.as(
"the handlers this test is about; an empty list would pass the check below for a"
+ " controller that lost its bodies or a scan that found nothing")
.containsExactlyInAnyOrder(
"reconcileOrphans(OrphanReconcileHttpRequest)", "forceDelete(ForceDeleteHttpRequest)");
assertThat(offenders)
.as(
"admin @RequestBody handlers without @Valid would silently drop any Bean Validation "
+ "constraint added to their DTO later (BE-INPUT-002)")
+ "constraint added to their DTO later")
.isEmpty();
}
}