Files
ccn/Packages/Infrastructure/Tests/Cases/Public/Middlewares/LocalizationMiddlewareTests.swift
T
javier 65b62681eb Project updates from Template (#1)
This PR contains the latest updates from the generic Website template, which have been added while working on #loud-amsterdam.

Reviewed-on: #1
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
2026-09-04 13:40:35 +00:00

116 lines
3.2 KiB
Swift

import Foundation
import HTTPTypes
import Hummingbird
import HummingbirdTesting
import NIOCore
import Testing
@testable import Infrastructure
@Suite(
"LocalizationMiddleware middleware",
.tags(.middleware)
)
struct LocalizationMiddlewareTests {
// MARK: Constants
private let app: Application = .init(router: {
let router = Router(context: StubRequestContext.self)
router.addMiddleware {
LocalizationMiddleware(bundle: .module)
}
router.get("language") { _, context in
context.language
}
router.get("de/language") { _, context in
context.language
}
return router
}())
// MARK: Functional tests
@Test
func `negotiates a supported language from the header`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/language",
method: .get,
headers: [.acceptLanguage: "de-DE,de;q=0.9"]
) { response in
#expect(String(buffer: response.body) == "de")
}
}
}
@Test
func `falls back to the default without a header`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/language",
method: .get
) { response in
#expect(String(buffer: response.body) == "en")
}
}
}
@Test
func `falls back to the default for an unsupported language`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/language",
method: .get,
headers: [.acceptLanguage: "fr-FR,fr;q=0.9"]
) { response in
#expect(String(buffer: response.body) == "en")
}
}
}
@Test
func `honours a supported lang query parameter over the header`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/language?lang=de",
method: .get,
headers: [.acceptLanguage: "en"]
) { response in
#expect(String(buffer: response.body) == "de")
}
}
}
/// A language's whole URL prefix answers in its language, so its not-found page does too.
@Test
func `pins the language a leading path segment names over the header`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/de/language",
method: .get,
headers: [.acceptLanguage: "en"]
) { response in
#expect(String(buffer: response.body) == "de")
}
}
}
@Test
func `negotiates the header when the lang query parameter is unsupported`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/language?lang=fr",
method: .get,
headers: [.acceptLanguage: "de"]
) { response in
#expect(String(buffer: response.body) == "de")
}
}
}
}