api-swift / Tests / IrdAPITests / Core / RequestBuilderTests.swift
523 words
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import Foundation
import Testing
@testable import IrdAPI

@Suite struct RequestBuilderTests {
    let op = IrdOperation(method: .get, pathTemplate: "/domains/check", module: "domains", name: "check", security: .anonymousOrKey)

    @Test func getCarriesBearerAndAcceptAndNoBody() async throws {
        let (client, http) = captureClient()
        _ = try await client.raw.request(method: .get, path: "/domains/check", query: [QueryItem("domain", "x.ro")])
        let r = try #require(http.last)
        #expect(r.httpMethod == "GET")
        #expect(r.url?.absoluteString == "https://api.ird.ro/domains/check?domain=x.ro")
        #expect(r.value(forHTTPHeaderField: "Authorization") == "Bearer ird_k")
        #expect(r.value(forHTTPHeaderField: "Accept") == "application/json")
        #expect(r.value(forHTTPHeaderField: "Content-Type") == nil)
        #expect(r.httpBody == nil)
    }

    @Test func noCredentialMeansNoAuthorization() async throws {
        let (client, http) = captureClient(apiKey: nil)
        _ = try await client.raw.request(method: .get, path: "/domains/example")
        #expect(http.last?.value(forHTTPHeaderField: "Authorization") == nil)
    }

    @Test func blankTokenMeansNoAuthorization() async throws {
        let (client, http) = captureClient(apiKey: "   ")
        _ = try await client.raw.request(method: .get, path: "/domains/example")
        #expect(http.last?.value(forHTTPHeaderField: "Authorization") == nil)
    }

    @Test func anonymousOperationsNeverSendTheBearer() async throws {
        let (client, http) = captureClient()
        _ = try await client.raw.request(method: .post, path: "/auth/device/start", security: .anonymous)
        #expect(http.last?.value(forHTTPHeaderField: "Authorization") == nil)
        _ = try await client.raw.request(method: .get, path: "/domains/check", security: .anonymousOrKey)
        #expect(http.last?.value(forHTTPHeaderField: "Authorization") == "Bearer ird_k")
    }

    @Test func queryEncodesSpacesAsPercent20AndKeepsOrder() {
        let q = RequestBuilder.queryString([QueryItem("q", "a b"), QueryItem("count", "3"), QueryItem("x", "a+b/c!'()*")])
        #expect(q == "?q=a%20b&count=3&x=a%2Bb%2Fc%21%27%28%29%2A")
        #expect(RequestBuilder.queryString([]) == "")
    }

    @Test func encodeKeepsUnreservedAndEscapesUnicode() {
        #expect(RequestBuilder.encode("AZaz09-_.~") == "AZaz09-_.~")
        #expect(RequestBuilder.encode("ș") == "%C8%99")
        #expect(RequestBuilder.encode("/orbitdb/zdpu An") == "%2Forbitdb%2Fzdpu%20An")
    }

    @Test func pathParamsAreEncodedAsOneSegment() throws {
        #expect(try RequestBuilder.fillPath("/dns/domains/{domain}/records", params: ["domain": "a b/c"]) == "/dns/domains/a%20b%2Fc/records")
        #expect(try RequestBuilder.fillPath("/p2p/apps/{id}/domains/{domain-id}", params: ["id": "a1", "domain-id": "d1"]) == "/p2p/apps/a1/domains/d1")
    }

    @Test func missingPathParamIsAConfigError() async {
        let (client, http) = captureClient()
        let e = await caught { _ = try await client.raw.request(method: .get, path: "/tunnels/{id}") }
        #expect(e == .config("Missing path parameter {id} for /tunnels/{id}"))
        #expect(http.count == 0)
    }

    @Test func clientHeadersOverrideComputedOnes() async throws {
        let (client, http) = captureClient(headers: ["Accept": "text/plain", "X-Trace": "1"])
        _ = try await client.raw.request(method: .get, path: "/domains/example")
        #expect(http.last?.value(forHTTPHeaderField: "Accept") == "text/plain")
        #expect(http.last?.value(forHTTPHeaderField: "X-Trace") == "1")
    }

    @Test func postSendsJSONBodyWithContentType() async throws {
        let (client, http) = captureClient()
        _ = try await client.raw.request(method: .post, path: "/ipfs/pins", body: ["cid": "bafy1", "name": "site"])
        let r = try #require(http.last)
        #expect(r.value(forHTTPHeaderField: "Content-Type") == "application/json")
        #expect(bodyJSON(r) == ["cid": "bafy1", "name": "site"])
    }

    @Test func deleteCanCarryABody() async throws {
        let (client, http) = captureClient()
        _ = try await client.raw.request(method: .delete, path: "/dns/domains/{domain}/records", params: ["domain": "x.ro"],
                                         body: ["name": "www", "type": "A"])
        let r = try #require(http.last)
        #expect(r.httpMethod == "DELETE")
        #expect(r.value(forHTTPHeaderField: "Content-Type") == "application/json")
        #expect(bodyJSON(r) == ["name": "www", "type": "A"])
    }

    @Test func baseURLTrailingSlashesAreStripped() async throws {
        var c = Configuration(apiKey: "ird_k")
        c.apiURL = URL(string: "https://example.test/api//")!
        let http = FakeHTTP(script: [json(200, "{}")])
        c.transport = http
        _ = try await IrdClient(configuration: c).raw.request(method: .get, path: "/domains/example")
        #expect(http.last?.url?.absoluteString == "https://example.test/api/domains/example")
    }

    @Test func timeoutIsAppliedToTheRequest() async throws {
        var c = Configuration(apiKey: "ird_k")
        c.timeout = 7
        let http = FakeHTTP(script: [json(200, "{}")])
        c.transport = http
        _ = try await IrdClient(configuration: c).raw.request(method: .get, path: "/domains/example")
        #expect(http.last?.timeoutInterval == 7)
    }

    @Test func absoluteURLRequestsCarryTheirOwnBearerAndContentType() async throws {
        let (client, http) = captureClient()
        _ = try await client.raw.request(method: .post, url: URL(string: "https://node.test/up/1")!, token: "grant-tok",
                                         query: [QueryItem("format", "car")], body: Data([1, 2, 3]))
        let r = try #require(http.last)
        #expect(r.url?.absoluteString == "https://node.test/up/1?format=car")
        #expect(r.value(forHTTPHeaderField: "Authorization") == "Bearer grant-tok")
        #expect(r.value(forHTTPHeaderField: "Content-Type") == "application/octet-stream")
        #expect(r.httpBody == Data([1, 2, 3]))
        _ = try await client.raw.request(method: .post, url: URL(string: "https://node.test/up/2")!, token: nil, body: Data())
        #expect(http.last?.value(forHTTPHeaderField: "Authorization") == nil)
    }
}

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/api-swift.git