p2p-swift / Tests / IrdP2PSignalingTests / TurnCredentialsTests.swift
230 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
import Foundation
import Testing
@testable import IrdP2PSignaling

@Suite struct TurnCredentialsTests {
    let creds = #"{"username":"1787000000:app:nonce","credential":"c3Vy","ttl":3600,"urls":["stun:p1.ap2p.ro:3478","turn:p1.ap2p.ro:3478?transport=udp"]}"#

    @Test func fetchesCachesAndRenewsBeforeExpiry() async {
        let http = FakeHTTP { _ in json(200, self.creds) }
        let clock = TestClock()
        let cache = IceServerCache(url: URL(string: "https://app.example.test/turn-credentials")!, origin: "https://o.example", http: http, clock: clock)
        let c = await cache.configuration()
        #expect(c.servers == [IceServer(urls: ["stun:p1.ap2p.ro:3478", "turn:p1.ap2p.ro:3478?transport=udp"], username: "1787000000:app:nonce", credential: "c3Vy")])
        #expect(http.last?.value(forHTTPHeaderField: "Origin") == "https://o.example")
        _ = await cache.configuration()
        #expect(http.count == 1)
        clock.advance(by: .seconds(3600 - 301))
        _ = await cache.configuration()
        #expect(http.count == 1)
        clock.advance(by: .seconds(2))
        _ = await cache.configuration()
        #expect(http.count == 2)
    }

    @Test func failureDegradesToEmptyAndRetriesAfter30s() async {
        let http = FakeHTTP { _ in json(403, #"{"error":"origin_not_allowed"}"#) }
        let clock = TestClock()
        let cache = IceServerCache(url: URL(string: "https://app.example.test/turn-credentials")!, origin: nil, http: http, clock: clock, relayOnly: true)
        let c = await cache.configuration()
        #expect(c.servers.isEmpty && c.relayOnly)
        _ = await cache.configuration()
        #expect(http.count == 1)
        clock.advance(by: .seconds(31))
        _ = await cache.configuration()
        #expect(http.count == 2)
    }

    @Test func oneInFlightFetchIsShared() async {
        let http = FakeHTTP { _ in try? await Task.sleep(for: .milliseconds(50)); return json(200, self.creds) }
        let cache = IceServerCache(url: URL(string: "https://app.example.test/turn-credentials")!, origin: nil, http: http, clock: TestClock())
        async let a = cache.configuration()
        async let b = cache.configuration()
        _ = await (a, b)
        #expect(http.count == 1)
    }

    @Test func noURLMeansNoServers() async {
        let http = FakeHTTP()
        let cache = IceServerCache(url: nil, origin: nil, http: http, clock: TestClock())
        #expect(await cache.configuration() == .none)
        #expect(http.count == 0)
    }
}

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