oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

1import XCTest
2
3@testable @_spi(Fixtures) import CallsKit
4
5/// Spec §15.26: the quality report built from fixture statistics — counts
6/// over the window, rates, the schema's enums and bounds — and nothing in
7/// it that names a person, a device or an address; the notices tallied;
8/// the device kinds; "Report a problem"'s anonymous diagnostics and its
9/// sheet's states. Spec §15.29: the window's round trip and jitter, the
10/// candidates, the dominant limit, the coders and codecs; and the
11/// automatic report's rules, gate and body.
12final class QualityReportTests: XCTestCase {
13 // MARK: - Fixtures
14
15 static let client = QualityClient(app: "mac", version: "0.4.8", os: "macos", osVersion: "26.0.1")
16
17 /// One connection's statistics, as WebRTC's report has them, with the
18 /// things that must never be reported planted in it: an address, a
19 /// port, a name in a track's label, a device's name.
20 static func sample(
21 generation: Int64 = 1, scale: Double = 1, screen: Bool = false, lostOut: Double = 3,
22 relayTLS: Bool = true, nan: Bool = false
23 ) -> QualityPeerSample {
24 var stats: [String: QualityStat] = [
25 "OA": QualityStat(
26 type: "outbound-rtp", numbers: ["bytesSent": 120_000 * scale, "packetsSent": 1500 * scale],
27 strings: ["kind": "audio", "mid": "0", "trackIdentifier": "Vicky Wallace's microphone"]),
28 "RIA": QualityStat(
29 type: "remote-inbound-rtp",
30 numbers: ["packetsLost": lostOut * scale, "roundTripTime": 0.042, "jitter": 0.004],
31 strings: ["kind": "audio", "localId": "OA"]),
32 "OV": QualityStat(
33 type: "outbound-rtp",
34 numbers: [
35 "bytesSent": 1_500_000 * scale, "packetsSent": 1800 * scale, "frameWidth": 1280, "frameHeight": 720,
36 "framesPerSecond": nan ? .nan : 29.97,
37 ],
38 strings: ["kind": "video", "mid": "1", "qualityLimitationReason": "bandwidth"]),
39 "IA": QualityStat(
40 type: "inbound-rtp",
41 numbers: [
42 "bytesReceived": 110_000 * scale, "packetsReceived": 1490 * scale, "packetsLost": 10 * scale,
43 "jitter": 0.012, "totalSamplesReceived": 1_440_000 * scale, "concealedSamples": 4800 * scale,
44 "insertedSamplesForDeceleration": 960 * scale, "removedSamplesForAcceleration": 480 * scale,
45 "jitterBufferDelay": 72_000 * 0.06 * scale, "jitterBufferEmittedCount": 72_000 * scale,
46 ],
47 strings: ["kind": "audio", "mid": "0"]),
48 "IV": QualityStat(
49 type: "inbound-rtp",
50 numbers: [
51 "bytesReceived": 1_200_000 * scale, "packetsReceived": 1700 * scale, "packetsLost": 5 * scale,
52 "jitter": 0.02, "freezeCount": 1 * scale, "totalFreezesDuration": 0.5 * scale,
53 "framesDecoded": 890 * scale, "framesDropped": 2 * scale, "frameWidth": 640, "frameHeight": 480,
54 "framesPerSecond": 30,
55 ],
56 strings: ["kind": "video", "mid": "1"]),
57 "T": QualityStat(type: "transport", strings: ["selectedCandidatePairId": "CP"]),
58 "CP": QualityStat(
59 type: "candidate-pair", numbers: ["currentRoundTripTime": 0.038, "nominated": 1],
60 strings: ["localCandidateId": "LC", "remoteCandidateId": "RC", "state": "succeeded"]),
61 "LC": QualityStat(
62 type: "local-candidate", numbers: ["port": 54321],
63 strings: [
64 "candidateType": relayTLS ? "relay" : "host", "protocol": "udp", "relayProtocol": "tls",
65 "address": "192.168.1.20", "url": "turns:relay.example.com:443",
66 ]),
67 "RC": QualityStat(
68 type: "remote-candidate", numbers: ["port": 61000],
69 strings: ["candidateType": "srflx", "protocol": "udp", "address": "203.0.113.7"]),
70 "MS": QualityStat(type: "media-source", strings: ["kind": "audio", "deviceName": "Paul's AirPods Pro"]),
71 ]
72 if screen {
73 stats["OS"] = QualityStat(
74 type: "outbound-rtp",
75 numbers: [
76 "bytesSent": 3_000_000 * scale, "packetsSent": 3000 * scale, "frameWidth": 1920, "frameHeight": 1080,
77 "framesPerSecond": 8,
78 ],
79 strings: ["kind": "video", "mid": "3", "qualityLimitationReason": "cpu"])
80 stats["IS"] = QualityStat(
81 type: "inbound-rtp",
82 numbers: ["bytesReceived": 900_000 * scale, "framesDecoded": 300 * scale, "freezeCount": 2 * scale],
83 strings: ["kind": "video", "mid": "4"])
84 }
85 return QualityPeerSample(
86 generation: generation, ownScreenMid: screen ? "3" : nil, screenMid: screen ? "4" : "", stats: stats)
87 }
88
89 func build(
90 _ builder: inout QualityReportBuilder, at now: Double, _ samples: [String: QualityPeerSample],
91 tally: QualityEventTally = QualityEventTally(), final: Bool = false
92 ) -> QualityReport {
93 var tally = tally
94 return builder.build(
95 at: now, samples: samples, events: &tally, client: Self.client,
96 devices: QualityDevices(input: "bluetooth", output: "built-in"), final: final)
97 }
98
99 // MARK: - Counts over the window
100
101 func testCountsAreTheWindowsAndRatesAreOverIt() throws {
102 var builder = QualityReportBuilder()
103 builder.start(at: 100)
104 _ = build(&builder, at: 130, ["abc123def": Self.sample(scale: 1)])
105 // Thirty seconds later every counter has doubled: the window's counts
106 // are the second half alone.
107 let report = build(&builder, at: 160, ["abc123def": Self.sample(scale: 2)])
108 XCTAssertEqual(report.seconds, 30)
109 XCTAssertNil(report.isFinal)
110 let peer = try XCTUnwrap(report.peers?.first)
111 XCTAssertEqual(peer.peer, "abc123def")
112 let outAudio = try XCTUnwrap(peer.out?.audio)
113 XCTAssertEqual(outAudio.packets, 1500)
114 XCTAssertEqual(outAudio.kbps, 32, "120,000 bytes in 30 s is 32 kbit/s")
115 XCTAssertEqual(outAudio.lost, 3)
116 XCTAssertEqual(outAudio.rtt, 42)
117 XCTAssertEqual(outAudio.jitter, 4)
118 let outVideo = try XCTUnwrap(peer.out?.video)
119 XCTAssertEqual(outVideo.kbps, 400)
120 XCTAssertEqual(outVideo.limit, "bandwidth")
121 XCTAssertEqual(outVideo.width, 1280)
122 XCTAssertEqual(outVideo.fps, 30, "rounded to a tenth")
123 let inAudio = try XCTUnwrap(peer.in?.audio)
124 XCTAssertEqual(inAudio.packets, 1490)
125 XCTAssertEqual(inAudio.lost, 10)
126 XCTAssertEqual(inAudio.jitter, 12)
127 XCTAssertEqual(inAudio.samples, 1_440_000)
128 XCTAssertEqual(inAudio.concealed, 4800)
129 XCTAssertEqual(inAudio.inserted, 960)
130 XCTAssertEqual(inAudio.removed, 480)
131 XCTAssertEqual(inAudio.jitterBufferMs, 60)
132 let inVideo = try XCTUnwrap(peer.in?.video)
133 XCTAssertEqual(inVideo.freezes, 1)
134 XCTAssertEqual(inVideo.freezeSeconds, 0.5)
135 XCTAssertEqual(inVideo.decoded, 890)
136 XCTAssertEqual(inVideo.dropped, 2)
137 XCTAssertNil(peer.in?.screen)
138 XCTAssertNil(peer.out?.screen)
139 XCTAssertEqual(peer.path, QualityPath(local: "relay", remote: "srflx", protocol: "tls"))
140 XCTAssertEqual(peer.rtt, 38)
141 }
142
143 func testTheFirstWindowOfAConnectionCountsFromItsStart() throws {
144 var builder = QualityReportBuilder()
145 builder.start(at: 0)
146 let report = build(&builder, at: 30, ["p1": Self.sample(scale: 1)])
147 XCTAssertEqual(report.peers?.first?.out?.audio?.packets, 1500)
148 }
149
150 func testANewGenerationOrACounterGoingBackStartsAgain() throws {
151 var builder = QualityReportBuilder()
152 builder.start(at: 0)
153 _ = build(&builder, at: 30, ["p1": Self.sample(generation: 1, scale: 4)])
154 // A new connection: its counts are its own, not less than the old one's.
155 var report = build(&builder, at: 60, ["p1": Self.sample(generation: 2, scale: 1)])
156 XCTAssertEqual(report.peers?.first?.in?.audio?.packets, 1490)
157 // The same connection, a counter gone backwards (a receiver rebuilt).
158 report = build(&builder, at: 90, ["p1": Self.sample(generation: 2, scale: 0.5)])
159 XCTAssertEqual(report.peers?.first?.in?.audio?.packets, 745)
160 }
161
162 func testScreensAreToldApartByMid() throws {
163 var builder = QualityReportBuilder()
164 builder.start(at: 0)
165 let report = build(&builder, at: 30, ["p1": Self.sample(screen: true)])
166 let peer = try XCTUnwrap(report.peers?.first)
167 XCTAssertEqual(peer.out?.screen?.width, 1920)
168 XCTAssertEqual(peer.out?.screen?.limit, "cpu")
169 XCTAssertEqual(peer.out?.video?.width, 1280, "the camera is not the screen")
170 XCTAssertEqual(peer.in?.screen?.decoded, 300)
171 XCTAssertEqual(peer.in?.screen?.freezes, 2)
172 XCTAssertEqual(peer.in?.video?.decoded, 890)
173 }
174
175 func testBoundsNaNAndNegativesAndThePeerCeiling() throws {
176 var builder = QualityReportBuilder()
177 builder.start(at: 0)
178 var samples: [String: QualityPeerSample] = [:]
179 for i in 0..<6 { samples["peer\(i)"] = Self.sample(lostOut: -5, nan: true) }
180 // A window longer than the schema's ten minutes.
181 let report = build(&builder, at: 900, samples)
182 XCTAssertEqual(report.seconds, 600)
183 XCTAssertEqual(report.peers?.count, 4, "no more than the schema's four")
184 XCTAssertEqual(report.peers?.map(\.peer), ["peer0", "peer1", "peer2", "peer3"])
185 let video = try XCTUnwrap(report.peers?.first?.out?.video)
186 XCTAssertNil(video.fps, "NaN is left out, not sent")
187 XCTAssertNil(report.peers?.first?.out?.audio?.lost, "a negative count is left out")
188 XCTAssertEqual(QualityReportBuilder.bound(2e6, QualityBounds.kbps), 1e6)
189 XCTAssertNil(QualityReportBuilder.bound(.infinity, 10))
190 XCTAssertNil(QualityReportBuilder.bound(-1, 10))
191 XCTAssertEqual(QualityReportBuilder.bound(1.26, 10), 1.3)
192 }
193
194 func testTheEnums() {
195 XCTAssertEqual(QualityWords.limit("none"), "none")
196 XCTAssertEqual(QualityWords.limit("cpu"), "cpu")
197 XCTAssertEqual(QualityWords.limit("something new"), "other")
198 XCTAssertNil(QualityWords.limit(""))
199 XCTAssertEqual(QualityWords.candidate("prflx"), "prflx")
200 XCTAssertEqual(QualityWords.candidate("mystery"), "unknown")
201 XCTAssertEqual(QualityWords.candidate(nil), "unknown")
202 XCTAssertEqual(QualityWords.transport("tcp", relayProtocol: nil, relay: false), "tcp")
203 XCTAssertEqual(QualityWords.transport("udp", relayProtocol: "tls", relay: true), "tls")
204 XCTAssertEqual(QualityWords.transport("udp", relayProtocol: "tcp", relay: true), "tcp")
205 XCTAssertEqual(QualityWords.transport("udp", relayProtocol: "udp", relay: true), "udp")
206 XCTAssertEqual(QualityWords.transport("udp", relayProtocol: "tls", relay: false), "udp")
207 XCTAssertEqual(QualityWords.transport(nil, relayProtocol: nil, relay: false), "unknown")
208 }
209
210 // MARK: - Nothing that names anyone
211
212 func testTheEncodedReportCarriesNoNamesAddressesOrDevices() throws {
213 var builder = QualityReportBuilder()
214 builder.start(at: 0)
215 var tally = QualityEventTally()
216 tally.observe(at: 1, call: false, reconnecting: ["p1"], cantHear: [])
217 let report = build(&builder, at: 30, ["p1": Self.sample(screen: true)], tally: tally, final: true)
218 let json = try XCTUnwrap(report.encoded())
219 for forbidden in [
220 "Vicky", "Wallace", "AirPods", "Paul", "192.168", "203.0.113", "54321", "61000", "relay.example.com",
221 "turns:", "address", "trackIdentifier", "deviceName",
222 ] {
223 XCTAssertFalse(json.contains(forbidden), "the report carries \(forbidden): \(json)")
224 }
225 // And it is the schema's shape.
226 let object = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
227 XCTAssertEqual(object["v"] as? Int, 1)
228 XCTAssertEqual(object["final"] as? Bool, true)
229 XCTAssertEqual(object["seconds"] as? Double, 30)
230 XCTAssertEqual((object["client"] as? [String: String])?["app"], "mac")
231 XCTAssertEqual((object["devices"] as? [String: String])?["input"], "bluetooth")
232 let peer = try XCTUnwrap((object["peers"] as? [[String: Any]])?.first)
233 XCTAssertNotNil(peer["in"], "\"in\" is the key, as the schema spells it")
234 XCTAssertNotNil((peer["path"] as? [String: Any])?["protocol"])
235 XCTAssertEqual((peer["events"] as? [String: Any])?["reconnecting"] as? Double, 1)
236 XCTAssertNil(object["isFinal"])
237 }
238
239 @MainActor func testTheClientIsDigitsAndDots() {
240 XCTAssertEqual(QualityClientInfo.version("0.4.8"), "0.4.8")
241 XCTAssertNil(QualityClientInfo.version("0.4.8 (dev)"))
242 XCTAssertNil(QualityClientInfo.version("dev"))
243 XCTAssertNil(QualityClientInfo.version("1..2"))
244 XCTAssertNil(QualityClientInfo.version(nil))
245 XCTAssertEqual(
246 QualityClientInfo.osVersion(OperatingSystemVersion(majorVersion: 26, minorVersion: 0, patchVersion: 1)), "26.0.1")
247 let current = QualityClientInfo.current()
248 XCTAssertEqual(current.app, "mac")
249 XCTAssertEqual(current.os, "macos")
250 XCTAssertNotNil(current.osVersion)
251 }
252
253 // MARK: - §15.29: the window's detail
254
255 /// A relayed connection, as WebRTC's report has it: this side gathered a
256 /// host, a srflx and a relay (TURN over TLS), the peer offered a srflx,
257 /// and the selected pair is relay to srflx. With `direct`, a srflx to
258 /// srflx pair also succeeded. Planted: addresses, ports, the relay's
259 /// url, the encoder's and decoder's implementation names and the codec's
260 /// format line, none of which may be reported.
261 static func relayed(
262 direct: Bool = false, rtt: Double = 0.12, totalRtt: Double? = 3.0, responses: Double? = 30,
263 pair: String = "CPrelay_srflx", audioJitter: Double = 0.018, limit: [String: Double]? = nil,
264 reason: String = "bandwidth"
265 ) -> QualityPeerSample {
266 var pairNumbers: [String: Double] = ["currentRoundTripTime": rtt, "nominated": 1]
267 pairNumbers["totalRoundTripTime"] = totalRtt
268 pairNumbers["responsesReceived"] = responses
269 var outVideo: [String: Double] = [
270 "bytesSent": 900_000, "packetsSent": 900, "frameWidth": 640, "frameHeight": 360, "framesPerSecond": 15,
271 ]
272 for (k, v) in limit ?? [:] { outVideo["qualityLimitationDurations." + k] = v }
273 var stats: [String: QualityStat] = [
274 "T": QualityStat(type: "transport", strings: ["selectedCandidatePairId": pair]),
275 pair: QualityStat(
276 type: "candidate-pair", numbers: pairNumbers,
277 strings: ["localCandidateId": "LR", "remoteCandidateId": "RS", "state": "succeeded"]),
278 "CPhost": QualityStat(
279 type: "candidate-pair", strings: ["localCandidateId": "LH", "remoteCandidateId": "RS", "state": "failed"]),
280 "LH": QualityStat(
281 type: "local-candidate", numbers: ["port": 50000],
282 strings: ["candidateType": "host", "protocol": "udp", "address": "192.168.1.20"]),
283 "LS": QualityStat(
284 type: "local-candidate", numbers: ["port": 50001, "relatedPort": 50000],
285 strings: [
286 "candidateType": "srflx", "protocol": "udp", "address": "198.51.100.4", "relatedAddress": "192.168.1.20",
287 "url": "stun:stun.example.com:3478",
288 ]),
289 "LR": QualityStat(
290 type: "local-candidate", numbers: ["port": 50002],
291 strings: [
292 "candidateType": "relay", "protocol": "udp", "relayProtocol": "tls", "address": "203.0.113.50",
293 "url": "turns:relay.example.com:443?transport=tcp",
294 ]),
295 "RS": QualityStat(
296 type: "remote-candidate", numbers: ["port": 61000],
297 strings: ["candidateType": "srflx", "protocol": "udp", "address": "203.0.113.7"]),
298 "OV": QualityStat(
299 type: "outbound-rtp", numbers: outVideo,
300 strings: [
301 "kind": "video", "mid": "1", "qualityLimitationReason": reason,
302 "encoderImplementation": "SimulcastEncoderAdapter (VideoToolbox)", "codecId": "COT",
303 ]),
304 "COT": QualityStat(
305 type: "codec", numbers: ["payloadType": 102],
306 strings: ["mimeType": "video/H264", "sdpFmtpLine": "level-asymmetry-allowed=1;profile-level-id=42e01f"]),
307 "IA": QualityStat(
308 type: "inbound-rtp", numbers: ["packetsReceived": 1500, "jitter": audioJitter],
309 strings: ["kind": "audio", "mid": "0", "codecId": "CIA"]),
310 "CIA": QualityStat(type: "codec", strings: ["mimeType": "audio/opus"]),
311 "IV": QualityStat(
312 type: "inbound-rtp",
313 numbers: ["packetsReceived": 1200, "jitter": 0.03, "framesDecoded": 450, "freezeCount": 0],
314 strings: ["kind": "video", "mid": "1", "decoderImplementation": "libvpx", "codecId": "CIV"]),
315 "CIV": QualityStat(type: "codec", strings: ["mimeType": "video/VP8"]),
316 ]
317 if direct {
318 stats["CPdirect"] = QualityStat(
319 type: "candidate-pair", strings: ["localCandidateId": "LS", "remoteCandidateId": "RS", "state": "succeeded"])
320 }
321 return QualityPeerSample(generation: 1, stats: stats)
322 }
323
324 func testARelayedConnectionSaysWhy() throws {
325 var builder = QualityReportBuilder()
326 builder.start(at: 0)
327 var report = build(&builder, at: 30, ["p1": Self.relayed()])
328 var peer = try XCTUnwrap(report.peers?.first)
329 XCTAssertEqual(peer.path, QualityPath(local: "relay", remote: "srflx", protocol: "tls"))
330 // This side found its public address, and nothing direct worked.
331 XCTAssertEqual(
332 peer.candidates,
333 QualityCandidates(
334 host: 1, srflx: 1, relay: 1, remoteSrflx: 1, directOk: false, localDirectOk: false, udpOk: false))
335 // And with a direct pair that worked beside it.
336 report = build(&builder, at: 60, ["p1": Self.relayed(direct: true)])
337 peer = try XCTUnwrap(report.peers?.first)
338 XCTAssertEqual(
339 peer.candidates,
340 QualityCandidates(host: 1, srflx: 1, relay: 1, remoteSrflx: 1, directOk: true, localDirectOk: true, udpOk: true))
341 // The booleans go even when false: the struct's presence is "measured".
342 var relayedOnly = QualityReportBuilder()
343 relayedOnly.start(at: 0)
344 let json = try XCTUnwrap(build(&relayedOnly, at: 30, ["p1": Self.relayed()]).encoded())
345 XCTAssertTrue(json.contains(#""directOk":false"#), json)
346 XCTAssertTrue(json.contains(#""localDirectOk":false"#), json)
347 XCTAssertTrue(json.contains(#""udpOk":false"#), json)
348 XCTAssertFalse(json.contains("remoteHost"), "a type with none is left out: \(json)")
349 }
350
351 func testNoCandidatesInTheStatisticsIsNoCandidates() throws {
352 var builder = QualityReportBuilder()
353 builder.start(at: 0)
354 var sample = Self.relayed()
355 sample.stats = sample.stats.filter { !$0.value.type.hasSuffix("-candidate") }
356 let report = build(&builder, at: 30, ["p1": sample])
357 XCTAssertNil(report.peers?.first?.candidates, "a side that cannot read them says nothing, not none")
358 }
359
360 func testARelayOverUDPAndAHostPairAreUDP() throws {
361 var sample = Self.relayed()
362 sample.stats["LR"]?.strings["relayProtocol"] = "udp"
363 var builder = QualityReportBuilder()
364 builder.start(at: 0)
365 var c = try XCTUnwrap(build(&builder, at: 30, ["p1": sample]).peers?.first?.candidates)
366 XCTAssertTrue(c.udpOk, "UDP to the relay, and the relay's leg is UDP")
367 XCTAssertFalse(c.localDirectOk)
368 XCTAssertFalse(c.directOk)
369 // A pair from this side's own address to the peer's relay: local
370 // direct, not direct.
371 sample = Self.relayed()
372 sample.stats["RR"] = QualityStat(type: "remote-candidate", strings: ["candidateType": "relay", "protocol": "udp"])
373 sample.stats["CPtheirs"] = QualityStat(
374 type: "candidate-pair", strings: ["localCandidateId": "LH", "remoteCandidateId": "RR", "state": "succeeded"])
375 c = try XCTUnwrap(build(&builder, at: 60, ["p1": sample]).peers?.first?.candidates)
376 XCTAssertTrue(c.localDirectOk)
377 XCTAssertFalse(c.directOk)
378 XCTAssertTrue(c.udpOk)
379 XCTAssertEqual(c.remoteRelay, 1)
380 }
381
382 func testTheEncodersDecodersAndCodecsAreEnums() throws {
383 var builder = QualityReportBuilder()
384 builder.start(at: 0)
385 let peer = try XCTUnwrap(build(&builder, at: 30, ["p1": Self.relayed()]).peers?.first)
386 XCTAssertEqual(peer.out?.video?.encoder, "hardware")
387 XCTAssertEqual(peer.out?.video?.codec, "h264")
388 XCTAssertEqual(peer.in?.video?.decoder, "software")
389 XCTAssertEqual(peer.in?.video?.codec, "vp8")
390 XCTAssertNil(peer.out?.audio, "nothing goes out here but the camera")
391 // The stack's own word wins over the name.
392 var sample = Self.relayed()
393 sample.stats["OV"]?.numbers["powerEfficientEncoder"] = 0
394 sample.stats["IV"]?.numbers["powerEfficientDecoder"] = 1
395 var again = QualityReportBuilder()
396 again.start(at: 0)
397 let other = try XCTUnwrap(build(&again, at: 30, ["p1": sample]).peers?.first)
398 XCTAssertEqual(other.out?.video?.encoder, "software")
399 XCTAssertEqual(other.in?.video?.decoder, "hardware")
400 }
401
402 func testTheCoderAndCodecTables() {
403 XCTAssertEqual(QualityWords.coder(impl: "libvpx", powerEfficient: true), "hardware")
404 XCTAssertEqual(QualityWords.coder(impl: "VideoToolbox", powerEfficient: false), "software")
405 XCTAssertEqual(QualityWords.coder(impl: nil, powerEfficient: true), "hardware")
406 for name in [
407 "VideoToolbox", "ExternalEncoder", "MediaCodec", "VAAPI", "V4L2", "D3D11", "DXVA2", "NVENC", "NVDEC",
408 "MediaFoundationVideoEncodeAccelerator", "QSV", "AMF",
409 ] {
410 XCTAssertEqual(QualityWords.coder(impl: name, powerEfficient: nil), "hardware", name)
411 }
412 for name in [
413 "libvpx", "OpenH264", "libaom", "dav1d", "FFmpeg", "libavcodec", "FallbackEncoder (libvpx)", "SoftwareH264",
414 ] {
415 XCTAssertEqual(QualityWords.coder(impl: name, powerEfficient: nil), "software", name)
416 }
417 XCTAssertEqual(QualityWords.coder(impl: "SomethingNew", powerEfficient: nil), "unknown")
418 XCTAssertNil(QualityWords.coder(impl: "", powerEfficient: nil))
419 XCTAssertNil(QualityWords.coder(impl: nil, powerEfficient: nil))
420 for (mime, codec) in [
421 ("video/VP8", "vp8"), ("video/vp9", "vp9"), ("video/H264", "h264"), ("video/H265", "h265"),
422 ("video/HEVC", "h265"), ("video/AV1", "av1"), ("audio/opus", "opus"), ("audio/PCMU", "other"),
423 ("video/rtx", "other"),
424 ] {
425 XCTAssertEqual(QualityWords.codec(mimeType: mime), codec, mime)
426 }
427 XCTAssertNil(QualityWords.codec(mimeType: nil))
428 XCTAssertNil(QualityWords.codec(mimeType: ""))
429 }
430
431 func testTheMeanRoundTripIsThePairsOwnOverTheWindow() throws {
432 var builder = QualityReportBuilder()
433 builder.start(at: 0)
434 // The first window: everything the pair has, 3 s over 30 responses.
435 var peer = try XCTUnwrap(build(&builder, at: 30, ["p1": Self.relayed()]).peers?.first)
436 XCTAssertEqual(peer.rttAvg, 100)
437 XCTAssertEqual(peer.rttMax, 120, "no readings yet: the last walk's")
438 // The next: 6 s more over 20 more responses.
439 peer = try XCTUnwrap(build(&builder, at: 60, ["p1": Self.relayed(totalRtt: 9, responses: 50)]).peers?.first)
440 XCTAssertEqual(peer.rttAvg, 300)
441 // A new pair counts from nothing, not from the old pair's totals.
442 peer = try XCTUnwrap(
443 build(&builder, at: 90, ["p1": Self.relayed(totalRtt: 4, responses: 20, pair: "CPnew")]).peers?.first)
444 XCTAssertEqual(peer.rttAvg, 200)
445 }
446
447 func testTheSamplerGivesTheWindowsMeanAndHighest() throws {
448 var builder = QualityReportBuilder()
449 builder.start(at: 0)
450 for (rtt, jitter) in [(0.1, 0.01), (0.5, 0.03), (0.2, 0.02)] {
451 builder.observe(samples: ["p1": Self.relayed(rtt: rtt, totalRtt: nil, responses: nil, audioJitter: jitter)])
452 }
453 // No pair totals: the mean is the readings'.
454 var peer = try XCTUnwrap(
455 build(&builder, at: 30, ["p1": Self.relayed(rtt: 0.15, totalRtt: nil, responses: nil)]).peers?.first)
456 XCTAssertEqual(peer.rttAvg, 266.7)
457 XCTAssertEqual(peer.rttMax, 500)
458 XCTAssertEqual(peer.rtt, 150, "the latest is still the latest")
459 XCTAssertEqual(peer.jitterAvg, 20)
460 XCTAssertEqual(peer.jitterMax, 30)
461 // The readings are the window's: the next one starts again, and its
462 // highest is at least the latest reading.
463 builder.observe(samples: ["p1": Self.relayed(rtt: 0.05, totalRtt: nil, responses: nil)])
464 peer = try XCTUnwrap(
465 build(&builder, at: 60, ["p1": Self.relayed(rtt: 0.09, totalRtt: nil, responses: nil)]).peers?.first)
466 XCTAssertEqual(peer.rttAvg, 50)
467 XCTAssertEqual(peer.rttMax, 90)
468 XCTAssertEqual(peer.jitterMax, 18)
469 // The camera's jitter when no audio arrives.
470 var noAudio = Self.relayed()
471 noAudio.stats.removeValue(forKey: "IA")
472 builder.observe(samples: ["p1": noAudio])
473 peer = try XCTUnwrap(build(&builder, at: 90, ["p1": noAudio]).peers?.first)
474 XCTAssertEqual(peer.jitterAvg, 30)
475 // Restarting the window forgets them.
476 builder.observe(samples: ["p1": Self.relayed(rtt: 2)])
477 builder.start(at: 100)
478 peer = try XCTUnwrap(build(&builder, at: 130, ["p1": Self.relayed()]).peers?.first)
479 XCTAssertEqual(peer.rttMax, 120)
480 XCTAssertNil(peer.jitterAvg)
481 }
482
483 func testTheLimitIsTheReasonThatHeldLongest() throws {
484 var builder = QualityReportBuilder()
485 builder.start(at: 0)
486 _ = build(&builder, at: 30, ["p1": Self.relayed(limit: ["bandwidth": 10, "cpu": 0, "none": 20, "other": 0])])
487 // Over the window: bandwidth 15 s, cpu 10 s, none 5 s, though the
488 // latest reason is none.
489 var video = try XCTUnwrap(
490 build(
491 &builder, at: 60, ["p1": Self.relayed(limit: ["bandwidth": 25, "cpu": 10, "none": 25, "other": 0], reason: "none")]
492 ).peers?.first?.out?.video)
493 XCTAssertEqual(video.limit, "bandwidth")
494 XCTAssertEqual(video.limitedBandwidthSeconds, 15)
495 XCTAssertEqual(video.limitedCpuSeconds, 10)
496 // A tie goes to bandwidth, and cpu beats none.
497 video = try XCTUnwrap(
498 build(
499 &builder, at: 90, ["p1": Self.relayed(limit: ["bandwidth": 30, "cpu": 15, "none": 30, "other": 0], reason: "none")]
500 ).peers?.first?.out?.video)
501 XCTAssertEqual(video.limit, "bandwidth")
502 video = try XCTUnwrap(
503 build(
504 &builder, at: 120, ["p1": Self.relayed(limit: ["bandwidth": 30, "cpu": 40, "none": 50, "other": 0], reason: "none")]
505 ).peers?.first?.out?.video)
506 XCTAssertEqual(video.limit, "cpu")
507 XCTAssertEqual(video.limitedBandwidthSeconds, 0, "measured, and none")
508 // Nothing moved: the latest reason.
509 video = try XCTUnwrap(
510 build(
511 &builder, at: 150, ["p1": Self.relayed(limit: ["bandwidth": 30, "cpu": 40, "none": 50, "other": 0], reason: "cpu")]
512 ).peers?.first?.out?.video)
513 XCTAssertEqual(video.limit, "cpu")
514 // No durations at all: the latest reason, and no seconds.
515 video = try XCTUnwrap(build(&builder, at: 180, ["p1": Self.relayed(reason: "other")]).peers?.first?.out?.video)
516 XCTAssertEqual(video.limit, "other")
517 XCTAssertNil(video.limitedBandwidthSeconds)
518 XCTAssertNil(video.limitedCpuSeconds)
519 }
520
521 func testWebRTCsDictionariesAndBooleansAreRead() {
522 let values: [String: Any] = [
523 "qualityLimitationDurations": ["bandwidth": NSNumber(value: 1.5), "cpu": NSNumber(value: 2), "none": NSNumber(value: 26.5)]
524 as NSDictionary,
525 "powerEfficientEncoder": NSNumber(value: true),
526 "encoderImplementation": "VideoToolbox" as NSString,
527 "ssrcs": [1, 2] as NSArray,
528 ]
529 let stat = QualityStat(type: "outbound-rtp", values: values)
530 XCTAssertEqual(stat.numbers["qualityLimitationDurations.bandwidth"], 1.5)
531 XCTAssertEqual(stat.numbers["qualityLimitationDurations.cpu"], 2)
532 XCTAssertEqual(stat.numbers["powerEfficientEncoder"], 1)
533 XCTAssertEqual(stat.strings["encoderImplementation"], "VideoToolbox")
534 XCTAssertNil(stat.numbers["ssrcs"])
535 }
536
537 func testTheScreensModeGoesOnTheScreen() throws {
538 var builder = QualityReportBuilder()
539 builder.start(at: 0)
540 var tally = QualityEventTally()
541 let peer = try XCTUnwrap(
542 builder.build(
543 at: 30, samples: ["p1": Self.sample(screen: true)], events: &tally, client: Self.client, devices: nil,
544 final: false, screenMode: "detail"
545 ).peers?.first)
546 XCTAssertEqual(peer.out?.screen?.mode, "detail")
547 XCTAssertNil(peer.out?.video?.mode, "the camera has no share mode")
548 // Not sharing: nowhere.
549 let none = try XCTUnwrap(
550 builder.build(
551 at: 60, samples: ["p1": Self.sample()], events: &tally, client: Self.client, devices: nil, final: false,
552 screenMode: "detail"
553 ).peers?.first)
554 XCTAssertNil(none.out?.screen)
555 }
556
557 func testTheDetailCarriesNoAddressesPortsUrlsOrNames() throws {
558 var builder = QualityReportBuilder()
559 builder.start(at: 0)
560 builder.observe(samples: ["p1": Self.relayed(direct: true)])
561 let report = build(
562 &builder, at: 30, ["p1": Self.relayed(direct: true, limit: ["bandwidth": 12, "cpu": 3, "none": 15, "other": 0])])
563 let json = try XCTUnwrap(report.encoded())
564 for forbidden in [
565 "192.168", "198.51.100", "203.0.113", "50000", "50001", "50002", "61000", "stun.example.com",
566 "relay.example.com", "turns:", "stun:", "VideoToolbox", "Simulcast", "libvpx", "profile-level-id", "H264",
567 "VP8", "CPrelay", "CPdirect", "address", "url", "Implementation", "mimeType", "codecId",
568 ] {
569 XCTAssertFalse(json.contains(forbidden), "the report carries \(forbidden): \(json)")
570 }
571 XCTAssertTrue(json.contains(#""encoder":"hardware""#), json)
572 XCTAssertTrue(json.contains(#""candidates":{"#), json)
573 }
574
575 // MARK: - §15.29: the automatic report
576
577 static func window(
578 freezes: Double? = nil, rttMax: Double? = nil, rtt: Double? = nil, outRtt: Double? = nil,
579 reconnecting: Double? = nil, peerReconnecting: Double? = nil, rebuilds: Double? = nil
580 ) -> QualityReport {
581 var peer = QualityPeer(peer: "p1", rtt: rtt, rttMax: rttMax)
582 if let freezes {
583 peer.in = QualityInbound(video: QualityInVideo(freezes: freezes - 1), screen: QualityInVideo(freezes: 1))
584 }
585 if outRtt != nil || rebuilds != nil {
586 peer.out = QualityOutbound(audio: QualityOutStream(rtt: outRtt), screen: QualityOutStream(rebuilds: rebuilds))
587 }
588 if let peerReconnecting { peer.events = QualityPeerEvents(reconnectingSeconds: peerReconnecting) }
589 var report = QualityReport(seconds: 30, client: client, peers: [peer, QualityPeer(peer: "p2")])
590 if let reconnecting { report.events = QualityCallEvents(reconnectingSeconds: reconnecting) }
591 return report
592 }
593
594 func testTheFactsOfAWindow() {
595 XCTAssertEqual(QualityTrouble.facts(Self.window()), QualityTrouble.Facts())
596 XCTAssertEqual(QualityTrouble.facts(Self.window(freezes: 4)).freezes, 4, "cameras and screens")
597 XCTAssertEqual(QualityTrouble.facts(Self.window(rttMax: 300, rtt: 900, outRtt: 200)).maxRtt, 900)
598 XCTAssertEqual(QualityTrouble.facts(Self.window(rttMax: 300, rtt: 100, outRtt: 1200)).maxRtt, 1200)
599 XCTAssertEqual(QualityTrouble.facts(Self.window(reconnecting: 2, peerReconnecting: 7)).reconnectingSeconds, 7)
600 XCTAssertEqual(QualityTrouble.facts(Self.window(reconnecting: 9, peerReconnecting: 7)).reconnectingSeconds, 9)
601 XCTAssertTrue(QualityTrouble.facts(Self.window(rebuilds: 1)).screenEscalated)
602 XCTAssertFalse(QualityTrouble.facts(Self.window(rebuilds: 0)).screenEscalated)
603 // Keyframes alone are the ladder's first step, not trouble.
604 var keyframes = Self.window()
605 keyframes.peers?[0].out = QualityOutbound(screen: QualityOutStream(keyframes: 5))
606 XCTAssertFalse(QualityTrouble.facts(keyframes).screenEscalated)
607 }
608
609 func testTheRulesNeedTwoWindowsForFreezesAndTheRoundTrip() {
610 typealias F = QualityTrouble.Facts
611 XCTAssertEqual(QualityTrouble.trigger(previous: F(freezes: 3), now: F(freezes: 3)), "freezes")
612 XCTAssertNil(QualityTrouble.trigger(previous: nil, now: F(freezes: 10)), "one window is not enough")
613 XCTAssertNil(QualityTrouble.trigger(previous: F(freezes: 2), now: F(freezes: 10)))
614 XCTAssertNil(QualityTrouble.trigger(previous: F(freezes: 10), now: F(freezes: 2)))
615 XCTAssertEqual(QualityTrouble.trigger(previous: F(maxRtt: 801), now: F(maxRtt: 900)), "rtt")
616 XCTAssertNil(QualityTrouble.trigger(previous: F(maxRtt: 800), now: F(maxRtt: 900)), "above, not at")
617 XCTAssertNil(QualityTrouble.trigger(previous: nil, now: F(maxRtt: 5000)))
618 XCTAssertEqual(QualityTrouble.trigger(previous: nil, now: F(reconnectingSeconds: 5.1)), "reconnecting")
619 XCTAssertNil(QualityTrouble.trigger(previous: nil, now: F(reconnectingSeconds: 5)))
620 XCTAssertEqual(QualityTrouble.trigger(previous: nil, now: F(screenEscalated: true)), "screen")
621 XCTAssertNil(QualityTrouble.trigger(previous: F(), now: F()))
622 // In AutoTriggers' order.
623 let everything = F(freezes: 5, maxRtt: 1000, reconnectingSeconds: 20, screenEscalated: true)
624 XCTAssertEqual(QualityTrouble.trigger(previous: everything, now: everything), "freezes")
625 XCTAssertEqual(
626 QualityTrouble.trigger(previous: F(maxRtt: 1000), now: F(freezes: 5, maxRtt: 1000, screenEscalated: true)), "rtt")
627 XCTAssertEqual(
628 QualityTrouble.trigger(previous: nil, now: F(reconnectingSeconds: 20, screenEscalated: true)), "reconnecting")
629 XCTAssertEqual(AutoReportRules.triggers, ["freezes", "rtt", "reconnecting", "screen"])
630 }
631
632 func testTheGateIsThreeACallTenMinutesApart() {
633 var gate = AutoReportGate()
634 XCTAssertTrue(gate.allows(at: 0))
635 gate.record(at: 0)
636 XCTAssertFalse(gate.allows(at: 599))
637 XCTAssertTrue(gate.allows(at: 600))
638 gate.record(at: 600)
639 gate.record(at: 1300)
640 XCTAssertEqual(gate.sent, 3)
641 XCTAssertFalse(gate.allows(at: 10_000), "three in one participation, and no more")
642 }
643
644 func testTheDecision() {
645 typealias F = QualityTrouble.Facts
646 let bad = F(freezes: 5)
647 let gate = AutoReportGate()
648 func decide(
649 enabled: Bool = true, stopped: Bool = false, final: Bool = false, gate: AutoReportGate = gate,
650 previous: F? = bad, now: F = bad, forced: String? = nil
651 ) -> String? {
652 AutoReportDecision.trigger(
653 previous: previous, now: now, gate: gate, at: 1000, enabled: enabled, stopped: stopped, final: final,
654 forced: forced)
655 }
656 XCTAssertEqual(decide(), "freezes")
657 XCTAssertNil(decide(enabled: false), "quality reports off in Settings: automatic reports off")
658 XCTAssertNil(decide(final: true), "the final report never sends one")
659 XCTAssertNil(decide(stopped: true), "the kill switch")
660 var spent = AutoReportGate()
661 spent.record(at: 900)
662 XCTAssertNil(decide(gate: spent), "ten minutes apart")
663 XCTAssertNil(decide(previous: F(), now: F()))
664 // The gate's forced trigger: whatever the call is like, but only where
665 // the rest allows.
666 XCTAssertEqual(decide(previous: nil, now: F(), forced: "screen"), "screen")
667 XCTAssertNil(decide(enabled: false, forced: "screen"))
668 XCTAssertNil(decide(final: true, forced: "screen"))
669 XCTAssertNil(decide(gate: spent, forced: "screen"))
670 XCTAssertNil(decide(previous: nil, now: F(), forced: "anything"), "not a trigger: the rules decide")
671 }
672
673 func testTheAutomaticReportsBodyHasNoNote() throws {
674 let body = AutoReportBody(trigger: "rtt", diagnostics: "peer abc123: unmuted", client: Self.client).encoded()
675 let object = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any])
676 XCTAssertEqual(Set(object.keys), ["trigger", "diagnostics", "client"])
677 XCTAssertEqual(object["trigger"] as? String, "rtt")
678 XCTAssertEqual(object["diagnostics"] as? String, "peer abc123: unmuted")
679 XCTAssertEqual((object["client"] as? [String: String])?["app"], "mac")
680 let long = AutoReportBody(
681 trigger: "freezes", diagnostics: String(repeating: "line of diagnostics\n", count: 10_000), client: Self.client
682 ).encoded()
683 XCTAssertLessThanOrEqual(long.utf8.count, QualityBounds.problemBody)
684 }
685
686 func testTheAutomaticReportsAnswersAndReference() throws {
687 XCTAssertEqual(AutoReportOutcome(bridgeAnswer: #"{"ref":"AB12CD34"}"#), .sent(ref: "AB12CD34"))
688 XCTAssertEqual(AutoReportOutcome(bridgeAnswer: #"{"outcome":"stop"}"#), .stop)
689 XCTAssertEqual(AutoReportOutcome(bridgeAnswer: #"{"outcome":"too-many"}"#), .notSent("too-many"))
690 XCTAssertEqual(AutoReportOutcome(bridgeAnswer: "nonsense"), .notSent("failed"))
691 var report = QualityReport(seconds: 30, client: Self.client)
692 XCTAssertFalse(try XCTUnwrap(report.encoded()).contains("autoReport"))
693 report.autoReport = "AB12CD34"
694 XCTAssertTrue(try XCTUnwrap(report.encoded()).contains(#""autoReport":"AB12CD34""#))
695 }
696
697 // MARK: - Notices
698
699 func testNoticesAreCountedWhenTheyBeginAndTimedWhileTheyShow() {
700 var tally = QualityEventTally()
701 tally.observe(at: 0, call: false, reconnecting: [], cantHear: ["b"])
702 tally.observe(at: 0.2, call: true, reconnecting: ["a"], cantHear: ["b"], noSound: ["a"])
703 tally.observe(at: 0.4, call: true, reconnecting: ["a"], cantHear: [])
704 // A gap of a minute (the Mac asleep) counts as no more than a second.
705 tally.observe(at: 60.4, call: false, reconnecting: [], cantHear: [], noSoundFromUs: ["c"], audioBlocked: ["c"])
706 tally.count(.keyframe, for: "a")
707 tally.count(.reattach, for: "c")
708 var builder = QualityReportBuilder()
709 builder.start(at: 0)
710 var mutable = tally
711 let report = builder.build(
712 at: 61, samples: [:], events: &mutable, client: Self.client, devices: nil, final: false)
713 XCTAssertEqual(report.events?.reconnecting, 1)
714 // Each look counts the time since the one before for what it sees.
715 XCTAssertEqual(report.events?.reconnectingSeconds, 0.4)
716 let peers = Dictionary(uniqueKeysWithValues: (report.peers ?? []).map { ($0.peer, $0) })
717 XCTAssertEqual(peers["a"]?.events?.reconnecting, 1)
718 XCTAssertEqual(peers["a"]?.events?.reconnectingSeconds, 0.4)
719 XCTAssertEqual(peers["a"]?.events?.noSound, true)
720 XCTAssertEqual(peers["a"]?.out?.screen?.keyframes, 1)
721 XCTAssertEqual(peers["b"]?.events?.cantHearSeconds, 0.2)
722 XCTAssertEqual(peers["c"]?.events?.noSoundFromUs, true)
723 XCTAssertEqual(peers["c"]?.events?.audioBlocked, true)
724 XCTAssertEqual(peers["c"]?.in?.screen?.reattaches, 1)
725 XCTAssertNil(peers["b"]?.events?.noSound)
726 }
727
728 func testANoticeStillShowingIsNotCountedAgainInTheNextWindow() {
729 var tally = QualityEventTally()
730 tally.observe(at: 0, call: true, reconnecting: ["a"], cantHear: [])
731 tally.observe(at: 1, call: true, reconnecting: ["a"], cantHear: [])
732 var builder = QualityReportBuilder()
733 builder.start(at: 0)
734 _ = builder.build(at: 1, samples: [:], events: &tally, client: Self.client, devices: nil, final: false)
735 tally.observe(at: 2, call: true, reconnecting: ["a"], cantHear: [])
736 let report = builder.build(at: 2, samples: [:], events: &tally, client: Self.client, devices: nil, final: false)
737 XCTAssertNil(report.events?.reconnecting, "the same notice, carried over")
738 XCTAssertEqual(report.events?.reconnectingSeconds, 1)
739 XCTAssertNil(report.peers?.first?.events?.reconnecting)
740 XCTAssertEqual(report.peers?.first?.events?.reconnectingSeconds, 1)
741 }
742
743 // MARK: - Devices
744
745 func testDeviceKindsFromCoreAudioTransports() {
746 XCTAssertEqual(DeviceKind.mac(transport: "built-in"), "built-in")
747 XCTAssertEqual(DeviceKind.mac(transport: "bluetooth"), "bluetooth")
748 XCTAssertEqual(DeviceKind.mac(transport: "usb"), "usb")
749 XCTAssertEqual(DeviceKind.mac(transport: "airplay"), "airplay")
750 XCTAssertEqual(DeviceKind.mac(transport: "virtual"), "virtual")
751 XCTAssertEqual(DeviceKind.mac(transport: "aggregate"), "virtual")
752 XCTAssertEqual(DeviceKind.mac(transport: "continuity"), "continuity")
753 XCTAssertEqual(DeviceKind.mac(transport: "thunderbolt"), "other")
754 XCTAssertEqual(DeviceKind.mac(transport: "0x12345678"), "other")
755 XCTAssertEqual(DeviceKind.mac(transport: nil), "unknown")
756 }
757
758 func testDeviceKindsFromAudioSessionPorts() {
759 // AVAudioSession.Port's raw values.
760 for (port, kind) in [
761 ("MicrophoneBuiltIn", "built-in"), ("Speaker", "built-in"), ("Receiver", "built-in"),
762 ("BluetoothHFP", "bluetooth"), ("BluetoothA2DPOutput", "bluetooth"), ("BluetoothLEOutput", "bluetooth"),
763 ("USBAudio", "usb"), ("Headphones", "wired"), ("MicrophoneWired", "wired"), ("AirPlay", "airplay"),
764 ("CarAudio", "other"), ("LineIn", "other"),
765 ] {
766 XCTAssertEqual(DeviceKind.ios(port: port), kind, port)
767 }
768 XCTAssertEqual(DeviceKind.ios(port: nil), "none")
769 }
770
771 func testEveryKindIsOneTheSchemaAllows() {
772 let allowed: Set = ["built-in", "bluetooth", "usb", "wired", "airplay", "virtual", "continuity", "other", "none", "unknown"]
773 for t in ["built-in", "bluetooth", "usb", "airplay", "virtual", "aggregate", "continuity", "display", "", "x"] {
774 XCTAssertTrue(allowed.contains(DeviceKind.mac(transport: t)))
775 }
776 for p in ["Speaker", "BluetoothHFP", "USBAudio", "Headphones", "AirPlay", "CarAudio", "", "x"] {
777 XCTAssertTrue(allowed.contains(DeviceKind.ios(port: p)))
778 }
779 }
780
781 // MARK: - Report a problem
782
783 static let roster = #"""
784 {"phase":"admitted","peer":"me0000aaaa","boot":"b","waiting":[],"peers":[
785 {"peer":"me0000aaaa","name":"Paul Campbell","kind":"member","gen":1},
786 {"peer":"abc123zzzz","name":"Vicky Wallace","kind":"member","gen":2,
787 "media":{"muted":true,"cameraOff":false,"noSoundFrom":["me0000aaaa"],"hearing":[]}}
788 ]}
789 """#
790
791 @MainActor func testTheAnonymousDiagnosticsNameNobody() {
792 let call = Call(playAudio: false)
793 call.showFixture(title: "Planning with Vicky", state: Self.roster)
794 let named = call.audioDiagnosticsText()
795 XCTAssertTrue(named.contains("Vicky Wallace: "), "Copy call diagnostics still names people")
796 let anonymous = call.anonymousDiagnosticsText()
797 XCTAssertTrue(anonymous.contains("peer abc123: "), anonymous)
798 XCTAssertTrue(anonymous.contains("muted"))
799 XCTAssertTrue(anonymous.contains("hears no sound from you"))
800 for forbidden in ["Vicky", "Wallace", "Paul Campbell", "Planning"] {
801 XCTAssertFalse(anonymous.contains(forbidden), "the report names \(forbidden)")
802 }
803 }
804
805 func testTheBridgesAnswers() {
806 XCTAssertEqual(ProblemOutcome(bridgeAnswer: #"{"ref":"K7Q2M9PD"}"#), .sent(ref: "K7Q2M9PD"))
807 XCTAssertEqual(ProblemOutcome(bridgeAnswer: #"{"outcome":"too-many"}"#), .tooMany)
808 XCTAssertEqual(ProblemOutcome(bridgeAnswer: #"{"outcome":"gone"}"#), .gone)
809 XCTAssertEqual(ProblemOutcome(bridgeAnswer: #"{"outcome":"failed"}"#), .failed)
810 XCTAssertEqual(ProblemOutcome(bridgeAnswer: "nonsense"), .failed)
811 XCTAssertEqual(ProblemOutcome(bridgeAnswer: #"{"ref":""}"#), .failed)
812 }
813
814 @MainActor func testTheSheetSendsAndShowsTheReference() async {
815 let sent = Box()
816 let model = ProblemReportModel { note in
817 await sent.set(note)
818 return .sent(ref: "K7Q2M9PD")
819 }
820 XCTAssertEqual(model.phase, .editing)
821 XCTAssertTrue(model.canSend, "the note is optional")
822 model.note = "Vicky sounded robotic"
823 XCTAssertEqual(model.counter, "21/1000")
824 await model.send()
825 XCTAssertEqual(model.phase, .sent(ref: "K7Q2M9PD"))
826 XCTAssertFalse(model.canSend, "sent once")
827 let note = await sent.value
828 XCTAssertEqual(note, "Vicky sounded robotic")
829 XCTAssertEqual(ProblemWords.reference("K7Q2M9PD"), "Reference K7Q2M9PD")
830 }
831
832 @MainActor func testTheSheetSaysWhyNotAndCanTryAgain() async {
833 let answers = Answers([.tooMany, .gone, .failed, .sent(ref: "ABCDEFGH")])
834 let model = ProblemReportModel { _ in await answers.next() }
835 await model.send()
836 XCTAssertEqual(model.phase, .refused("Too many reports from this call — try again in a minute."))
837 XCTAssertTrue(model.canSend)
838 await model.send()
839 XCTAssertEqual(model.phase, .refused("This call can no longer be reported."))
840 await model.send()
841 XCTAssertEqual(model.phase, .refused("The report could not be sent."))
842 await model.send()
843 XCTAssertEqual(model.phase, .sent(ref: "ABCDEFGH"))
844 }
845
846 @MainActor func testTheNoteIsAThousandCharactersAsTheServerCountsThem() {
847 let model = ProblemReportModel { _ in .failed }
848 model.note = String(repeating: "é", count: 1200)
849 XCTAssertEqual(model.note.unicodeScalars.count, 1000)
850 XCTAssertEqual(model.counter, "1000/1000")
851 }
852
853 func testTheWordsAreTheRulings() {
854 XCTAssertEqual(
855 ProblemWords.disclosure, "Sends this call's connection diagnostics to the Calls server log. No audio or video.")
856 XCTAssertEqual(ProblemWords.sent, "Sent — thank you")
857 XCTAssertEqual(
858 QualityReporting.disclosure, "Calls sends anonymous connection quality reports to help fix call problems.")
859 }
860
861 func testAProblemReportFitsTheServersLimit() throws {
862 let body = ProblemReportBody(
863 note: "x", diagnostics: String(repeating: "line of diagnostics\n", count: 10_000), client: Self.client
864 ).encoded()
865 XCTAssertLessThanOrEqual(body.utf8.count, QualityBounds.problemBody)
866 let object = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any])
867 XCTAssertEqual(object["note"] as? String, "x")
868 XCTAssertTrue((object["diagnostics"] as? String)?.hasPrefix("(earlier lines cut)") == true)
869 }
870
871 func testTheReportingSwitchIsOnUnlessTurnedOff() throws {
872 let defaults = try XCTUnwrap(UserDefaults(suiteName: "quality-\(UUID().uuidString)"))
873 XCTAssertTrue(QualityReporting.enabled(defaults))
874 defaults.set(false, forKey: QualityReporting.enabledKey)
875 XCTAssertFalse(QualityReporting.enabled(defaults))
876 }
877
878 @MainActor func testAnEndedCallOffersReportAProblem() {
879 let ended = CallNotices.notices(
880 phase: "ended", status: "This meeting has ended", sharingScreen: false, screenNote: "", floor: false)
881 XCTAssertEqual(ended.first?.action, .reportProblem)
882 let call = Call(playAudio: false)
883 XCTAssertFalse(call.canReportProblem, "no call, nothing to report")
884 call.reportProblem()
885 XCTAssertNil(call.problemReport)
886 }
887}
888
889private actor Box {
890 var value = ""
891 func set(_ v: String) { value = v }
892}
893
894private actor Answers {
895 var queue: [ProblemOutcome]
896 init(_ queue: [ProblemOutcome]) { self.queue = queue }
897 func next() -> ProblemOutcome { queue.removeFirst() }
898}
899