# Testing

> Canonical URL: https://docs.mountaya.com/en/sdks/swift/testing/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Test Swift code that calls Mountaya with no network: answer requests yourself, pin the clock, script the map and navigation, and build errors.

Every part of the SDK your code talks to can be answered by your test: the network, the clocks, the map's renderer and navigation.

## Test code that calls the API

Every request leaves through an `HTTPExchange`. Hand the client your own, and it answers with no network:

```swift
import Foundation
import MountayaClient
import Testing

struct Answered: HTTPExchange {
  func send(_ request: ExchangeRequest) async throws -> ExchangeResponse {
    ExchangeResponse(status: 200, body: ExchangeBody(Data(#"{"data": []}"#.utf8)))
  }
}

@Test func listsNoActivities() async throws {
  let mountaya = try Mountaya(
    credential: .publishable(key: "pk_your_publishable_key"), exchange: Answered())
  let activities = try await mountaya.studio.activities.getActivities()
  #expect(activities.data.isEmpty)
}
```

- `HTTPExchange` is one method, `send(_:) async throws -> ExchangeResponse`. `ExchangeRequest` carries `method`, `url`, `headers` (read in any case with `header(_:)`) and `body`; `ExchangeResponse(status:headers:body:)` takes an `ExchangeBody` of bytes, of `chunks:` (an `AsyncThrowingStream<Data, any Error>` for an event stream) or `reading:`.
- The platform's exchange is `SystemExchange`, over `URLSession`: it keeps no cookie and follows no redirect, so no credential reaches a host the contract never named.
- Every transport rule runs over your exchange as over the network: retries, idempotency keys, the error ladder. Answer `429` with a `Retry-After` to test your back-off handling.
- The client checks only each key's and token's prefix where it is built (`pk_`, `sk_`, `sess_`, `share_`), so `pk_your_publishable_key` builds a test client; your exchange never sends it anywhere.

## Control time

The client measures every wait on the clock you hand it. A test that answers `503` and then `200` sees the call retried with no real wait:

```swift
import Foundation
import MountayaClient
import Testing

// Skips every wait under a second, a retry's backoff; an attempt's deadline still runs.
struct SkippingClock: Clock {
  var now: ContinuousClock.Instant { ContinuousClock.now }
  var minimumResolution: Duration { .zero }

  func sleep(until deadline: ContinuousClock.Instant, tolerance: Duration?) async throws {
    guard now.duration(to: deadline) >= .seconds(1) else { return }
    try await ContinuousClock().sleep(until: deadline, tolerance: tolerance)
  }
}

actor Attempts {
  private(set) var count = 0
  func next() -> Int {
    count += 1
    return count
  }
}

struct UnavailableOnce: HTTPExchange {
  let attempts = Attempts()

  func send(_ request: ExchangeRequest) async throws -> ExchangeResponse {
    if await attempts.next() == 1 { return ExchangeResponse(status: 503) }
    return ExchangeResponse(status: 200, body: ExchangeBody(Data(#"{"data": []}"#.utf8)))
  }
}

@Test func retriesAfterA503() async throws {
  let exchange = UnavailableOnce()
  let mountaya = try Mountaya(
    credential: .publishable(key: "pk_your_publishable_key"), exchange: exchange,
    clock: SkippingClock())
  let activities = try await mountaya.studio.activities.getActivities()
  #expect(activities.data.isEmpty)
  #expect(await exchange.attempts.count == 2)
}
```

- `Mountaya(clock:random:wallClock:)` and `SessionTokenEngine(mint:clock:wallClock:)`: every wait and budget is measured on the `Clock<Duration>` you give (a test clock of yours, or a package such as swift-clocks). The attempt's deadline sleeps on the same clock as the backoff does, racing the exchange, so a clock that skips every wait would expire each attempt at once: skip the short waits, or advance a manual clock in steps.
- The SDK ships no test clock: the sample's `SkippingClock` is yours to copy. A `503` with no `Retry-After` waits a jittered backoff of at most 500 ms before the first retry, which it skips. Every jitter and drawn key comes from the `RandomSource` you give, and the instant a `Retry-After` date and a session's `expires_at` are read against comes from the `WallClock` you give.
- `constructWebhookEvent(…, now:)` pins the clock a webhook delivery is judged by ([receive webhooks](https://docs.mountaya.com/en/sdks/swift/webhooks.md#test)).
- In SwiftUI, `\.mountayaClock` is the `WallClock` the layers panel lays its time slider around.

## Script the map

`ScriptedMapSurface` stands in for the renderer, so a test drives a `MapEngine` with no MapLibre:

```swift
import MountayaClient
import MountayaElements
import Testing

@MainActor
@Test func aTapReachesTheMap() async throws {
  let map = MapEngine(client: try Mountaya(credential: .publishable(key: "pk_your_publishable_key")))
  let surface = ScriptedMapSurface(drawing: map)
  var events = map.events().makeAsyncIterator()

  surface.tap(at: [400, 300], position: [6.8712, 45.9231])

  guard case .tap(let tap) = await events.next() else {
    Issue.record("no tap")
    return
  }
  #expect(tap.position == [6.8712, 45.9231])
}
```

- `ScriptedMapSurface(drawing:canvas:zoomLimits:)` draws the engine's state nowhere and plays what a renderer tells it: `tap(at:position:)`, `longTap`, `hover`, `leave`, `drawFrame()`, `loadStyle()`, `failStyle()`, `loadTile(of:)`, `failRequest(url:status:source:superseded:cause:)`. It records what the engine asked of it: `frames`, `moves`, `queries`, `relabelled`; `rendered` sets what a point query answers.
- It builds and runs on every platform, so the map's logic tests on macOS and Linux with no simulator.

## Script navigation

`ScriptedNavigationEngine` is a navigation engine whose route requests your test answers:

```swift
import MountayaGeo
import Testing

@MainActor
@Test func arrivesInArgentiere() throws {
  let navigation = ScriptedNavigationEngine<String>()
  navigation.start("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
  try navigation.sent[0].answer(
    NavigationRoute(line: [[6.8712, 45.9231], [6.9271, 45.9822]], duration: 9_600))

  try navigation.setPosition([6.9271, 45.9822])
  #expect(navigation.state.status == .arrived)
}
```

Code that takes any `NavigationEngine` runs the same over this engine and over `DeviceNavigationEngine`.

- `sent` lists each route request in order as a `ScriptedRouteRequest`, with its `request`, `answer(_:)` and `fail(_:)` (each throws `ScriptedAnswerError` when answered twice).
- `ScriptedNavigationEngine` reports exactly what `DeviceNavigationEngine` reports: the same status, progress and arrival, off the route past 50 m, and a new route asked for by `reroute(_:)` alone.
- Every engine is bound to the main actor, and so is a test of one.

## Build errors

Build the failure your code handles through its public initializer:

```swift
import MountayaClient
import Testing

func message(for error: MountayaError) -> String {
  if case .api(let failure) = error, failure.kind == .notFound { return "Gone" }
  return "Try again"
}

@Test func saysGoneOnA404() {
  #expect(message(for: .api(APIError(status: 404))) == "Gone")
  #expect(message(for: .connection(ConnectionError())) == "Try again")
}
```

- `APIError(status:errors:metadata:retryAfter:requestId:rateLimit:etag:idempotencyKey:)` derives `kind` from the status (and the first entry's code for the two idempotency 409s); entries are `ErrorEntry(message:code:path:)`.
- `ConnectionError(idempotencyKey:cause:)`, `ConfigurationError(message:idempotencyKey:cause:)`, `SelectionError(path:message:)`, `WebhookSignatureError(reason:message:)`, `LocationError(kind:cause:)`, `SpeechError(kind:cause:)` and `MapError(kind:name:)` are public too.
- An exchange that answers the API's error envelope with a status exercises the real decoding instead.

## Next steps

- [Troubleshooting](https://docs.mountaya.com/en/sdks/swift/troubleshooting.md): The errors developers hit first.
- [Errors and retries](https://docs.mountaya.com/en/sdks/swift/errors.md): The error cases your tests build.
