Test URLSession Cookies With A Real Local Server

Your login tests pass. Then one account starts sending another account’s cookie, or a redirect quietly changes the request you thought you were testing.

A mock can return the correct JSON while missing both problems. It is an excellent employee: it does exactly what you told it to do.

For these cases, give URLSession a real HTTP connection to a disposable local server. We will verify that cookies survive between requests, remain separate between sessions that need isolation, and travel through a redirect. The fixture stays inside the test target and needs no running backend.

The sample uses Xcode 27 / Swift 6.4, Swift Testing, and Hummingbird 2.27.0. Its package targets iOS 17 and macOS 14 or later. These are established networking behaviors, not new OS 27 features.

Choose the layer you actually need to test

Donny Wals’s network-testing article separates view-model mocks from request tests using URLProtocol. That is useful motivation for deciding what each test proves. This article adds a transport test: Foundation itself must process the HTTP response and prepare the next request.

The distinction matters. In a Swift Forums discussion, Apple’s Quinn explains that a custom URLProtocol changes session behavior. Returning a Set-Cookie header from a stub does not establish that the ordinary HTTP stack stored and resent that cookie.

There is a separate isolation problem. A shared response handler can be protected by an actor and still produce this sequence: test A registers a response, test B replaces it, then A makes its request. Each access is safe; the test arrangement is wrong. .serialized can be useful, but its documented scope does not coordinate unrelated suites.

Keep fast in-memory tests for decoding, errors, and view state. Add a few real-transport tests where cookies, redirects, or your session configuration are part of the promise. The broader Stack Overflow question about UI-test network injection already has answers; this fixture addresses the narrower transport problem, not injection into a separately launched UI-test app.

Make the server a test dependency

Download the complete sample package, or create a directory with this Package.swift:

// swift-tools-version: 6.4
import PackageDescription

let package = Package(
    name: "TransportChecks",
    platforms: [.iOS(.v17), .macOS(.v14)],
    dependencies: [
        .package(
            url: "https://github.com/hummingbird-project/hummingbird.git",
            exact: "2.27.0"
        )
    ],
    targets: [
        .testTarget(
            name: "TransportChecksTests",
            dependencies: [
                .product(name: "Hummingbird", package: "hummingbird"),
                .product(name: "HummingbirdTesting", package: "hummingbird")
            ],
            swiftSettings: [.swiftLanguageMode(.v6)]
        )
    ]
)

Put all the remaining Swift blocks, in order, into TransportTests.swift, inside the package’s Tests → TransportChecksTests folder. Run swift test from the package directory for macOS, or open Package.swift in Xcode and run its package test scheme on an iOS Simulator. The download includes the resolved dependency versions.

Hummingbird brings a substantial server-library dependency graph. Use it only in the test target; do not add these products to the shipping app. It earns its place here by owning the listener, readiness, and shutdown. If you already have a suitable local HTTP fixture, keep it and adapt the assertions below.

Give each fixture its own listener

The server has a login route, a cookie echo, and two redirect routes. Its cookies contain fixed test values, never credentials.

import Foundation
import Hummingbird
import HummingbirdTesting
import Testing

@concurrent nonisolated func withServer<Value: Sendable>(
    cookie: String,
    _ body: @escaping @Sendable (URL) async throws -> Value
) async throws -> Value {
    let router = Router(context: BasicRequestContext.self)

    router.get("login") { _, _ in
        Response(
            status: .ok,
            headers: [.setCookie: "session=\(cookie); Path=/; HttpOnly"],
            body: .init()
        )
    }
    router.get("echo") { request, _ in
        let bytes = try await request.body.collect(upTo: 4096)
        return "\(request.method.rawValue)|\(request.headers[.cookie] ?? "")|\(String(buffer: bytes))"
    }
    router.post("echo") { request, _ in
        let bytes = try await request.body.collect(upTo: 4096)
        return "\(request.method.rawValue)|\(request.headers[.cookie] ?? "")|\(String(buffer: bytes))"
    }
    router.post("redirect302") { _, _ in
        Response(
            status: .found,
            headers: [.location: "/echo",
                      .setCookie: "session=\(cookie); Path=/"],
            body: .init()
        )
    }
    router.post("redirect307") { _, _ in
        Response(
            status: .temporaryRedirect,
            headers: [.location: "/echo",
                      .setCookie: "session=\(cookie); Path=/"],
            body: .init()
        )
    }

    return try await Application(router: router).test(.live) { client in
        let port = try #require(client.port)
        let baseURL = try #require(URL(string: "http://localhost:\(port)/"))
        return try await body(baseURL)
    }
}

nonisolated func makeSession() -> URLSession {
    let configuration = URLSessionConfiguration.ephemeral
    configuration.urlCache = nil
    configuration.timeoutIntervalForRequest = 5
    configuration.timeoutIntervalForResource = 5
    return URLSession(configuration: configuration)
}

@concurrent nonisolated func fetch(
    _ session: URLSession,
    _ url: URL,
    method: String = "GET",
    body: String? = nil
) async throws -> String {
    var request = URLRequest(url: url)
    request.httpMethod = method
    request.httpBody = body.map { Data($0.utf8) }
    let (data, response) = try await session.data(for: request)
    let http = try #require(response as? HTTPURLResponse)
    try #require(http.statusCode == 200)
    return String(decoding: data, as: UTF8.self)
}

Hummingbird’s live test implementation waits for its server’s assigned port before invoking the closure and handles shutdown afterward. The test application binds localhost with port 0, allowing the operating system to choose a port. There is no fixed port to collide with another test and no sleep pretending to establish readiness.

We only use the supplied client’s port. Our requests go through Foundation’s URLSession, not Hummingbird’s test client. Changing .live to .router would remove the real connection and change what this test proves.

The five-second limits bound slow requests in this tiny fixture; adjust them for your test environment if needed. They do not establish readiness or a production timeout policy. @concurrent keeps these helpers off the caller’s actor, including projects using MainActor default isolation.

This test gives two sessions identical cookie names and different values. Both servers use localhost, so we cannot accidentally rely on host separation.

@Test(arguments: 0..<5)
func independentSessionsKeepTheirCookies(iteration: Int) async throws {
    try await withServer(cookie: "alpha\(iteration)") { left in
        try await withServer(cookie: "beta\(iteration)") { right in
            let first = makeSession()
            let second = makeSession()
            defer {
                first.invalidateAndCancel()
                second.invalidateAndCancel()
            }

            async let loginA = fetch(first, left.appendingPathComponent("login"))
            async let loginB = fetch(second, right.appendingPathComponent("login"))
            _ = try await (loginA, loginB)

            async let echoA = fetch(first, left.appendingPathComponent("echo"))
            async let echoB = fetch(second, right.appendingPathComponent("echo"))
            let echoed = try await (echoA, echoB)

            #expect(echoed.0 == "GET|session=alpha\(iteration)|")
            #expect(echoed.1 == "GET|session=beta\(iteration)|")
        }
    }
}

Waiting for both logins matters. A sequence that logs in and immediately checks one session, then repeats for the other, can miss a shared store: the first assertion finishes before the second login contaminates it.

The parameterized cases can also run alongside one another. Each owns its listener and creates new configurations. We do not clear a global cookie jar during teardown, which could delete a cookie another test is still using.

Apple documents httpCookieStorage as the store used by tasks in sessions based on a configuration. An ephemeral configuration supplies a private, in-memory store. That does not mean each session built from the same configuration receives an independent jar.

Here is a passing test that deliberately demonstrates the mistake:

@Test func reusedConfigurationSharesItsCookieStore() async throws {
    try await withServer(cookie: "first") { left in
        try await withServer(cookie: "second") { right in
            let configuration = URLSessionConfiguration.ephemeral
            configuration.timeoutIntervalForResource = 5
            let first = URLSession(configuration: configuration)
            let second = URLSession(configuration: configuration)
            defer {
                first.invalidateAndCancel()
                second.invalidateAndCancel()
            }

            _ = try await fetch(first, left.appendingPathComponent("login"))
            _ = try await fetch(second, right.appendingPathComponent("login"))
            let echoed = try await fetch(first, left.appendingPathComponent("echo"))

            // The first session now sends the second login's cookie.
            #expect(echoed == "GET|session=second|")
        }
    }
}

The second login replaces the first cookie. Different localhost ports do not save us: HTTP cookies do not use ports as an isolation boundary.

For independent test sessions, call a factory that creates a fresh ephemeral configuration each time, as makeSession() does. Fresh .default configurations still use the shared cookie store by default. Reusing an ephemeral configuration or explicitly assigning shared httpCookieStorage defeats the isolation here. In a real app, intentional sharing may be correct; the test should match the account/session boundary your product actually promises.

Check the request after the redirect

A final 200 response is not enough. Check what reached the destination: method, cookie, and body.

@Test(arguments: [302, 307])
func redirectChangesTheRequestAsExpected(status: Int) async throws {
    try await withServer(cookie: "redirected") { base in
        let session = makeSession()
        defer { session.invalidateAndCancel() }

        let echoed = try await fetch(
            session,
            base.appendingPathComponent("redirect\(status)"),
            method: "POST",
            body: "payload"
        )

        let expected = status == 302
            ? "GET|session=redirected|"
            : "POST|session=redirected|payload"
        #expect(echoed == expected)
    }
}

On the tested Foundation runtimes, the 302 becomes a GET with no request body; the 307 retains the POST and payload. Both carry the cookie supplied by the redirect response. RFC 9110 allows a client to change POST to GET for a 302; it does not say every HTTP client must do so. A 307 preserves the method when automatically followed.

This checks same-host redirects in an ephemeral session. It is not an allowlist for redirect destinations. If your app rejects redirects or permits only specific origins, install its actual delegate in the fixture and test both acceptance and rejection, including whether the rejected destination receives a request.

Keep the claim as small as the fixture

The downloaded package includes additional checks for a rejected oversized body, HTTP status handling, a custom-protocol cookie control, and listener shutdown after a thrown test body. Those distinguish an HTTP error response from a transport error and exercise the fixture’s failure path.

The exact article examples were compiled with warnings treated as errors and exercised on macOS 27.0.1 and iOS 27 Simulator, in ordinary and MainActor default-isolation builds. The macOS runner also exercised parallel test cases; the iOS run used serial cases, each still issuing its two login requests concurrently. Hummingbird can log shutdown diagnostics when the test body throws; the cleanup check verifies that the listener closes, not that shutdown is silent.

Plain loopback HTTP does not establish production TLS, proxy behavior, HTTP/2 or HTTP/3, background transfers, Safari or WebKit cookie sharing, or a real authentication server’s policy. No physical-device or older-OS runtime coverage is claimed. Run the same focused checks with your production session factory where configuration is the thing under test; keep separate staging/device tests for the boundaries this fixture cannot exercise.

The useful question is no longer just “did my mock return the right bytes?” It is “did the next real request carry the state and method my app depends on?” That is a much harder bug to wave through with a green test.