Testing a custom reactive WebGraphQlInterceptor with Netlfix DGS

I have a working WebGraphQLInterceptor that does some authorization checks based on a combination of authentication and GraphQL query parameters.

I want to write unit tests that test my CustomGraphQlInterceptor in isolation, not as part of the larger servlet we’re building. But I cannot get the code to execute during a test.

Simplified code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Component
class CustomGraphQlInterceptor : WebGraphQlInterceptor {
private val logger = LoggerFactory.getLogger(javaClass)
// you can ignore IDE errors about being unable to Autowire this bean, it will
// successfully autowire at runtime.
@Suppress("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private lateinit var externalAuthorizationService: ExternalAuthorizationService
override fun intercept(
request: WebGraphQlRequest,
chain: WebGraphQlInterceptor.Chain,
): Mono<WebGraphQlResponse> {
logger.info("Validating request: $request")
logger.info("Context is ${ReactiveSecurityContextHolder.getContext()}")
return ReactiveSecurityContextHolder.getContext().flatMap { securityContext ->
val authentication = securityContext.authentication
if (authentication is JwtAuthenticationToken) {
val externalId = authentication.tokenAttributes["externalId"] as? String
val queryVariable = request.variables["queryVariable"]
val isAuthorized: Boolean = externalAuthorizationService.isAuthorized(externalId, queryVariable)
if (!isAuthorized) {
return@flatMap Mono.error(IllegalAccessException("not authorized"))
}
return@flatMap chain.next(request)
}
}
</code>
<code>@Component class CustomGraphQlInterceptor : WebGraphQlInterceptor { private val logger = LoggerFactory.getLogger(javaClass) // you can ignore IDE errors about being unable to Autowire this bean, it will // successfully autowire at runtime. @Suppress("SpringJavaInjectionPointsAutowiringInspection") @Autowired private lateinit var externalAuthorizationService: ExternalAuthorizationService override fun intercept( request: WebGraphQlRequest, chain: WebGraphQlInterceptor.Chain, ): Mono<WebGraphQlResponse> { logger.info("Validating request: $request") logger.info("Context is ${ReactiveSecurityContextHolder.getContext()}") return ReactiveSecurityContextHolder.getContext().flatMap { securityContext -> val authentication = securityContext.authentication if (authentication is JwtAuthenticationToken) { val externalId = authentication.tokenAttributes["externalId"] as? String val queryVariable = request.variables["queryVariable"] val isAuthorized: Boolean = externalAuthorizationService.isAuthorized(externalId, queryVariable) if (!isAuthorized) { return@flatMap Mono.error(IllegalAccessException("not authorized")) } return@flatMap chain.next(request) } } </code>
@Component
class CustomGraphQlInterceptor : WebGraphQlInterceptor {
  private val logger = LoggerFactory.getLogger(javaClass)

  // you can ignore IDE errors about being unable to Autowire this bean, it will
  // successfully autowire at runtime.
  @Suppress("SpringJavaInjectionPointsAutowiringInspection")
  @Autowired
  private lateinit var externalAuthorizationService: ExternalAuthorizationService

  override fun intercept(
    request: WebGraphQlRequest,
    chain: WebGraphQlInterceptor.Chain,
  ): Mono<WebGraphQlResponse> {
    logger.info("Validating request: $request")
    logger.info("Context is  ${ReactiveSecurityContextHolder.getContext()}")
    return ReactiveSecurityContextHolder.getContext().flatMap { securityContext ->
      val authentication = securityContext.authentication
      if (authentication is JwtAuthenticationToken) {
       val externalId = authentication.tokenAttributes["externalId"] as? String

      val queryVariable = request.variables["queryVariable"]
      
      val isAuthorized: Boolean = externalAuthorizationService.isAuthorized(externalId, queryVariable)

     if (!isAuthorized) {
       return@flatMap Mono.error(IllegalAccessException("not authorized"))
     }
     return@flatMap chain.next(request)
  }
}

My test is like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@ExtendWith(SpringExtension::class)
@SpringBootTest(
classes = [DgsAutoConfiguration::class, TestConfig::class],
webEnvironment = WebEnvironment.RANDOM_PORT,
properties = ["spring.main.web-application-type=reactive", "spring.profiles.active=test"],
)
@TestExecutionListeners(
ReactorContextTestExecutionListener::class,
mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS,
)
class SupplierGraphQlInterceptorTest {
@Autowired
private lateinit var customGraphQlInterceptor: CustomGraphQlInterceptor
@MockkBean
private lateinit var externalAuthorizationService: ExternalAuthorizationService
@BeforeEach
fun setupAuthorized() {
TestSecurityContextHolder.setAuthentication(
JwtAuthenticationToken(
Jwt(
"token",
Instant.now(),
Instant.MAX,
mapOf(
"alg" to "none",
),
mapOf(
"externalId" to "1",
),
),
),
)
}
@Test
fun testUserIsAuthorized() {
val request =
WebGraphQlRequest(
URI("http://localhost:8080/graphql"), // uri
HttpHeaders(CollectionUtils.toMultiValueMap(mapOf())), // headers
null, // cookies
null, // remote address
mapOf(), // attributes
mapOf( // body
"query" to "{someQuery{id name}}",
"operationName" to "POST",
"variables" to mapOf("queryVariable" to "ABC"),
),
"1", // id
null, // local
)
every {
authorizationService.isAuthorized(1, "ABC")
} returns true
val chain = mockk<WebGraphQlInterceptor.Chain>()
every { chain.next(any()) } returns Mono.just(mockk<WebGraphQlResponse>())
StepVerifier
.create(
supplierGraphQlInterceptor.intercept(request, chain),
).expectNextMatches { it is WebGraphQlResponse }
.verifyComplete()
}
}
</code>
<code>@Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) @ExtendWith(SpringExtension::class) @SpringBootTest( classes = [DgsAutoConfiguration::class, TestConfig::class], webEnvironment = WebEnvironment.RANDOM_PORT, properties = ["spring.main.web-application-type=reactive", "spring.profiles.active=test"], ) @TestExecutionListeners( ReactorContextTestExecutionListener::class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS, ) class SupplierGraphQlInterceptorTest { @Autowired private lateinit var customGraphQlInterceptor: CustomGraphQlInterceptor @MockkBean private lateinit var externalAuthorizationService: ExternalAuthorizationService @BeforeEach fun setupAuthorized() { TestSecurityContextHolder.setAuthentication( JwtAuthenticationToken( Jwt( "token", Instant.now(), Instant.MAX, mapOf( "alg" to "none", ), mapOf( "externalId" to "1", ), ), ), ) } @Test fun testUserIsAuthorized() { val request = WebGraphQlRequest( URI("http://localhost:8080/graphql"), // uri HttpHeaders(CollectionUtils.toMultiValueMap(mapOf())), // headers null, // cookies null, // remote address mapOf(), // attributes mapOf( // body "query" to "{someQuery{id name}}", "operationName" to "POST", "variables" to mapOf("queryVariable" to "ABC"), ), "1", // id null, // local ) every { authorizationService.isAuthorized(1, "ABC") } returns true val chain = mockk<WebGraphQlInterceptor.Chain>() every { chain.next(any()) } returns Mono.just(mockk<WebGraphQlResponse>()) StepVerifier .create( supplierGraphQlInterceptor.intercept(request, chain), ).expectNextMatches { it is WebGraphQlResponse } .verifyComplete() } } </code>
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@ExtendWith(SpringExtension::class)
@SpringBootTest(
    classes = [DgsAutoConfiguration::class, TestConfig::class],
    webEnvironment = WebEnvironment.RANDOM_PORT,
    properties = ["spring.main.web-application-type=reactive", "spring.profiles.active=test"],
)
@TestExecutionListeners(
  ReactorContextTestExecutionListener::class,
  mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS,
)
class SupplierGraphQlInterceptorTest {
  @Autowired
  private lateinit var customGraphQlInterceptor: CustomGraphQlInterceptor

  @MockkBean
  private lateinit var externalAuthorizationService: ExternalAuthorizationService

  @BeforeEach
  fun setupAuthorized() {
    TestSecurityContextHolder.setAuthentication(
      JwtAuthenticationToken(
        Jwt(
          "token",
          Instant.now(),
          Instant.MAX,
          mapOf(
            "alg" to "none",
          ),
          mapOf(
            "externalId" to "1",
          ),
        ),
      ),
    )
  }

  @Test
  fun testUserIsAuthorized() {
    val request =
      WebGraphQlRequest(
        URI("http://localhost:8080/graphql"), // uri
        HttpHeaders(CollectionUtils.toMultiValueMap(mapOf())), // headers
        null, // cookies
        null, // remote address
        mapOf(), // attributes
        mapOf( // body
          "query" to "{someQuery{id name}}",
          "operationName" to "POST",
          "variables" to mapOf("queryVariable" to "ABC"),
        ),
        "1", // id
        null, // local
      )

    every {
      authorizationService.isAuthorized(1, "ABC")
    } returns true

    val chain = mockk<WebGraphQlInterceptor.Chain>()
    every { chain.next(any()) } returns Mono.just(mockk<WebGraphQlResponse>())

    StepVerifier
      .create(
        supplierGraphQlInterceptor.intercept(request, chain),
      ).expectNextMatches { it is WebGraphQlResponse }
      .verifyComplete()
  }
}

This fails with

java.lang.AssertionError: expectation “expectNextMatches” failed (expected: onNext(); actual: onComplete())

I am new to DGS, Spring, and kotlin so I am sure I am doing at least several things wrong here.

I was able to solve this. Using ReactorContextTestExecutionListener was a mistake, this can be done much cleaner:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@ExtendWith(SpringExtension::class)
@SpringBootTest(
classes = [DgsAutoConfiguration::class, TestConfig::class],
webEnvironment = WebEnvironment.RANDOM_PORT,
properties = ["spring.main.web-application-type=reactive", "spring.profiles.active=test"],
)
class CustomGraphQlInterceptorTest {
@Autowired
private lateinit var customGraphQlInterceptor: CustomGraphQlInterceptor
@MockkBean
private lateinit var externalAuthorizationService: ExternalAuthorizationService
@Test
fun testUserIsAuthorized() {
val request =
WebGraphQlRequest(
URI("http://localhost:8080/graphql"), // uri
HttpHeaders(CollectionUtils.toMultiValueMap(mapOf())), // headers
null, // cookies
null, // remote address
mapOf(), // attributes
mapOf( // body
"query" to "{someQuery{id name}}",
"operationName" to "POST",
"variables" to mapOf("queryVariable" to "ABC"),
),
"1", // id
null, // local
)
every {
authorizationService.isAuthorized(1, "ABC")
} returns true
val jwt =
JwtAuthenticationToken(
Jwt(
"token",
Instant.now(),
Instant.MAX,
mapOf(
"alg" to "none",
),
mapOf(
"externalId" to 1,
),
),
)
val securityContext: SecurityContext = mockk()
every { securityContext.authentication } returns jwt
val chain = mockk<WebGraphQlInterceptor.Chain>()
every { chain.next(any()) } returns Mono.just(mockk<WebGraphQlResponse>())
StepVerifier
.create(
supplierGraphQlInterceptor.intercept(request, chain).contextWrite(
ReactiveSecurityContextHolder
.withSecurityContext(Mono.just(securityContext)),
),
).expectNextMatches { it is WebGraphQlResponse }
.verifyComplete()
}
}
</code>
<code>@Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) @ExtendWith(SpringExtension::class) @SpringBootTest( classes = [DgsAutoConfiguration::class, TestConfig::class], webEnvironment = WebEnvironment.RANDOM_PORT, properties = ["spring.main.web-application-type=reactive", "spring.profiles.active=test"], ) class CustomGraphQlInterceptorTest { @Autowired private lateinit var customGraphQlInterceptor: CustomGraphQlInterceptor @MockkBean private lateinit var externalAuthorizationService: ExternalAuthorizationService @Test fun testUserIsAuthorized() { val request = WebGraphQlRequest( URI("http://localhost:8080/graphql"), // uri HttpHeaders(CollectionUtils.toMultiValueMap(mapOf())), // headers null, // cookies null, // remote address mapOf(), // attributes mapOf( // body "query" to "{someQuery{id name}}", "operationName" to "POST", "variables" to mapOf("queryVariable" to "ABC"), ), "1", // id null, // local ) every { authorizationService.isAuthorized(1, "ABC") } returns true val jwt = JwtAuthenticationToken( Jwt( "token", Instant.now(), Instant.MAX, mapOf( "alg" to "none", ), mapOf( "externalId" to 1, ), ), ) val securityContext: SecurityContext = mockk() every { securityContext.authentication } returns jwt val chain = mockk<WebGraphQlInterceptor.Chain>() every { chain.next(any()) } returns Mono.just(mockk<WebGraphQlResponse>()) StepVerifier .create( supplierGraphQlInterceptor.intercept(request, chain).contextWrite( ReactiveSecurityContextHolder .withSecurityContext(Mono.just(securityContext)), ), ).expectNextMatches { it is WebGraphQlResponse } .verifyComplete() } } </code>
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@ExtendWith(SpringExtension::class)
@SpringBootTest(
    classes = [DgsAutoConfiguration::class, TestConfig::class],
    webEnvironment = WebEnvironment.RANDOM_PORT,
    properties = ["spring.main.web-application-type=reactive", "spring.profiles.active=test"],
)
class CustomGraphQlInterceptorTest {
  @Autowired
  private lateinit var customGraphQlInterceptor: CustomGraphQlInterceptor

  @MockkBean
  private lateinit var externalAuthorizationService: ExternalAuthorizationService
@Test
  fun testUserIsAuthorized() {
    val request =
      WebGraphQlRequest(
        URI("http://localhost:8080/graphql"), // uri
        HttpHeaders(CollectionUtils.toMultiValueMap(mapOf())), // headers
        null, // cookies
        null, // remote address
        mapOf(), // attributes
        mapOf( // body
          "query" to "{someQuery{id name}}",
          "operationName" to "POST",
          "variables" to mapOf("queryVariable" to "ABC"),
        ),
        "1", // id
        null, // local
      )

    every {
      authorizationService.isAuthorized(1, "ABC")
    } returns true

    val jwt =
      JwtAuthenticationToken(
        Jwt(
          "token",
          Instant.now(),
          Instant.MAX,
          mapOf(
            "alg" to "none",
          ),
          mapOf(
            "externalId" to 1,
          ),
        ),
      )

    val securityContext: SecurityContext = mockk()
    every { securityContext.authentication } returns jwt

    val chain = mockk<WebGraphQlInterceptor.Chain>()
    every { chain.next(any()) } returns Mono.just(mockk<WebGraphQlResponse>())

    StepVerifier
      .create(
        supplierGraphQlInterceptor.intercept(request, chain).contextWrite(
          ReactiveSecurityContextHolder
            .withSecurityContext(Mono.just(securityContext)),
        ),
      ).expectNextMatches { it is WebGraphQlResponse }
      .verifyComplete()
  }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật