From 6acf5513bc3ffaf2caafaf71bd0b42400f958053 Mon Sep 17 00:00:00 2001 From: Connor Ricks Date: Thu, 10 Oct 2024 17:59:58 -0400 Subject: [PATCH] Add a controller test that includes middleware (#565) --- .../ControllerTests.swift | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Tests/HummingbirdRouterTests/ControllerTests.swift b/Tests/HummingbirdRouterTests/ControllerTests.swift index b9028a0a..c4ec85ab 100644 --- a/Tests/HummingbirdRouterTests/ControllerTests.swift +++ b/Tests/HummingbirdRouterTests/ControllerTests.swift @@ -100,4 +100,49 @@ final class ControllerTests: XCTestCase { } } } + + func testRouterControllerWithMiddleware() async throws { + struct TestMiddleware: RouterMiddleware { + func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { + var response = try await next(request, context) + response.headers[.middleware] = "TestMiddleware" + return response + } + } + + struct ChildController: RouterController { + typealias Context = BasicRouterRequestContext + var body: some RouterMiddleware { + Get("foo") { _,_ in "foo" } + } + } + + struct ParentController: RouterController { + typealias Context = BasicRouterRequestContext + var body: some RouterMiddleware { + RouteGroup("parent") { + TestMiddleware() + ChildController() + Get("bar") { _,_ in "bar" } + } + } + } + + let router = RouterBuilder(context: BasicRouterRequestContext.self) { + ParentController() + } + + let app = Application(responder: router) + try await app.test(.router) { client in + try await client.execute(uri: "/parent/foo", method: .get) { + XCTAssertEqual($0.headers[.middleware], "TestMiddleware") + XCTAssertEqual(String(buffer: $0.body), "foo") + } + + try await client.execute(uri: "/parent/bar", method: .get) { + XCTAssertEqual($0.headers[.middleware], "TestMiddleware") + XCTAssertEqual(String(buffer: $0.body), "bar") + } + } + } }