-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMockBackend.swift
More file actions
963 lines (839 loc) · 40.7 KB
/
Copy pathMockBackend.swift
File metadata and controls
963 lines (839 loc) · 40.7 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2025-Present Datadog, Inc.
*/
import Compression
import Foundation
// MARK: - MockBackend
/// A mock HTTP backend that handles all Datadog SDK exporter endpoints.
/// Stores received payloads and returns configurable responses so integration
/// tests can verify SDK behaviour end-to-end without hitting real Datadog servers.
///
/// Usage:
/// ```swift
/// let backend = MockBackend()
/// try backend.start()
/// // Configure endpoint in your SDK: .other(testsBaseURL: backend.baseURL, logsBaseURL: backend.baseURL)
/// // ... run tests ...
/// backend.waitForSpans()
/// let spans = backend.requests.allSpans
/// backend.stop()
/// ```
public final class MockBackend {
public struct Config: Sendable {
/// Returned for POST /api/v2/libraries/tests/services/setting
public var settings: Settings
/// Returned for POST /api/v2/ci/libraries/tests
public var knownTests: KnownTestsMap
/// Returned for POST /api/v2/ci/tests/skippable
public var skippableTests: [SkippableTest]
/// Correlation ID included in the skippable tests response.
public var skippableTestsCorrelationId: String
/// Returned for GET /api/v2/test/libraries/test-management/tests
public var testManagement: TestManagementMap
public init(settings: Settings = .init(),
knownTests: KnownTestsMap = [:],
skippableTests: [SkippableTest] = [],
skippableTestsCorrelationId: String = "mock-correlation-id",
testManagement: TestManagementMap = [:])
{
self.settings = settings
self.knownTests = knownTests
self.skippableTests = skippableTests
self.skippableTestsCorrelationId = skippableTestsCorrelationId
self.testManagement = testManagement
}
}
public struct Requests: Sendable {
/// All decoded span envelopes received so far.
public var spanEnvelopes: [SpanEnvelope] = []
/// All log batches received so far.
public var logs: [[Log]] = []
/// All decoded coverage payloads received so far.
public var coverage: [CoveragePayload] = []
/// Raw bodies of all settings requests made by the SDK.
public var settings: [Data] = []
/// Raw bodies of all known-tests requests.
public var knownTests: [Data] = []
/// Raw bodies of all skippable-tests requests.
public var skippableTests: [Data] = []
/// Raw bodies of all test-management requests.
public var testManagement: [Data] = []
/// Raw bodies of all git search-commits requests.
public var searchCommits: [Data] = []
/// All packfiles received so far.
public var packfile: [Data] = []
/// Raw bodies of all telemetry (apmtelemetry) requests.
public var telemetry: [Data] = []
/// All spans across all received envelopes.
public var allSpans: [Span] { spanEnvelopes.flatMap(\.allSpans) }
/// All spans across all received envelopes.
public var allInfoSpans: [Span] { spanEnvelopes.flatMap(\.infoSpans) }
/// All test-type spans across all received envelopes.
public var allTestSpans: [Span] { spanEnvelopes.flatMap(\.testSpans) }
/// All `test_suite_end` events across all received envelopes.
public var allSuiteEnds: [TestSpan] { spanEnvelopes.flatMap(\.suiteEndEvents) }
/// All `test_module_end` events across all received envelopes.
public var allModuleEnds: [TestSpan] { spanEnvelopes.flatMap(\.moduleEndEvents) }
/// All `test_session_end` events across all received envelopes.
public var allSessionEnds: [TestSpan] { spanEnvelopes.flatMap(\.sessionEndEvents) }
/// All individual log entries across all batches.
public var allLogs: [Log] { logs.flatMap { $0 } }
/// All individual coverage entries across all payloads.
public var allCoverages: [TestCoverage] { coverage.flatMap(\.coverages) }
/// All `generate-metrics` (count/gauge/rate) series across every captured
/// telemetry batch.
public var telemetryMetricSeries: [TelemetrySeries] { MockBackend.parseTelemetry(telemetry).metrics }
/// All `distributions` series across every captured telemetry batch.
public var telemetryDistributionSeries: [TelemetrySeries] { MockBackend.parseTelemetry(telemetry).distributions }
/// Telemetry request types observed (e.g. `app-started`, `generate-metrics`,
/// `distributions`, `app-closing`).
public var telemetryEventTypes: Set<String> { MockBackend.parseTelemetry(telemetry).events }
}
// Thread safety.
private let _lock = NSLock()
// MARK: - Configuration (thread-safe read via computed property)
private var _configuration: Config = .init()
public var configuration: Config {
get { _lock.withLock { _configuration } }
set { _lock.withLock { _configuration = newValue } }
}
// MARK: - Received Data (thread-safe read via computed property)
private var _requests: Requests = .init()
public var requests: Requests { _lock.withLock { _requests } }
// MARK: - Server
private var _server: HttpTestServer!
public var serverPort: Int { _server.serverPort }
/// Base URL for this backend, e.g. `http://127.0.0.1:12345`.
/// Pass this to `Endpoint.other(testsBaseURL:logsBaseURL:)` when configuring the SDK.
public var baseURL: URL { _server.baseURL }
public init() {}
deinit { stop() }
// MARK: - Lifecycle
public func start() throws {
_server = .init() { [weak self] request, response in
guard let self else {
response.sendResponse(status: .internalServerError,
contentType: "application/json",
body: Data("{}".utf8))
return
}
let res = self.route(request: request)
response.sendResponse(status: res.status, contentType: res.contentType, body: res.body)
}
try _server.start()
}
public func stop() {
guard let _server else { return }
_server.stop()
self._server = nil
}
/// Clears all received data without affecting configuration.
public func reset() {
_lock.withLock { _requests = .init() }
}
// MARK: - Wait Helpers
/// Blocks until at least `count` span envelopes have been received, or `timeout` elapses.
@discardableResult
public func waitForSpans(count: Int = 1, timeout: TimeInterval = 10) -> Bool {
poll(timeout: timeout) { self._lock.withLock { self._requests.spanEnvelopes.count >= count } }
}
/// Blocks until at least `count` log batches have been received, or `timeout` elapses.
@discardableResult
public func waitForLogs(count: Int = 1, timeout: TimeInterval = 10) -> Bool {
poll(timeout: timeout) { self._lock.withLock { self._requests.logs.count >= count } }
}
/// Blocks until at least `count` coverage payloads have been received, or `timeout` elapses.
@discardableResult
public func waitForCoverage(count: Int = 1, timeout: TimeInterval = 10) -> Bool {
poll(timeout: timeout) { self._lock.withLock { self._requests.coverage.count >= count } }
}
/// Blocks until at least `count` settings requests have been received, or `timeout` elapses.
@discardableResult
public func waitForSettings(count: Int = 1, timeout: TimeInterval = 10) -> Bool {
poll(timeout: timeout) { self._lock.withLock { self._requests.settings.count >= count } }
}
/// Blocks until at least `count` telemetry batches have been received, or `timeout` elapses.
@discardableResult
public func waitForTelemetry(count: Int = 1, timeout: TimeInterval = 10) -> Bool {
poll(timeout: timeout) { self._lock.withLock { self._requests.telemetry.count >= count } }
}
private func poll(timeout: TimeInterval, condition: () -> Bool) -> Bool {
let deadline = Date(timeIntervalSinceNow: timeout)
while Date() < deadline {
if condition() { return true }
Thread.sleep(forTimeInterval: 0.05)
}
return condition()
}
// MARK: - Routing
private func route(request: HTTPTestRequest) -> (status: HTTPTestResponseSender.Status, contentType: String, body: Data) {
let body = request.head.headers.first(name: "content-encoding")?.lowercased() == "deflate"
? (request.body._zlibInflated ?? request.body) : request.body
switch request.head.path {
case "/api/v2/citestcycle":
if let envelope = try? JSONDecoder().decode(SpanEnvelope.self, from: body) {
_lock.withLock { _requests.spanEnvelopes.append(envelope) }
}
return (.ok, "application/json", Data("{}".utf8))
case "/api/v2/logs":
if let logs = try? JSONDecoder().decode([Log].self, from: body) {
_lock.withLock { _requests.logs.append(logs) }
}
return (.ok, "application/json", Data("{}".utf8))
case "/api/v2/citestcov":
if let payload = parseCoveragePayload(headers: request.head.headers, rawBody: body) {
_lock.withLock { _requests.coverage.append(payload) }
}
return (.ok, "application/json", Data("{}".utf8))
case "/api/v2/libraries/tests/services/setting":
_lock.withLock { _requests.settings.append(body) }
return (.ok, "application/json", buildSettingsResponse(requestId: extractRequestId(from: body)))
case "/api/v2/ci/libraries/tests":
_lock.withLock { _requests.knownTests.append(body) }
return (.ok, "application/json", buildKnownTestsResponse(requestId: extractRequestId(from: body)))
case "/api/v2/ci/tests/skippable":
_lock.withLock { _requests.skippableTests.append(body) }
return (.ok, "application/json", buildSkippableTestsResponse())
case "/api/v2/git/repository/search_commits":
_lock.withLock { _requests.searchCommits.append(body) }
return (.ok, "application/json", Data("{\"data\":[]}".utf8))
case "/api/v2/git/repository/packfile":
_lock.withLock { _requests.packfile.append(body) }
return (.ok, "application/json", Data("{}".utf8))
case "/api/v2/apmtelemetry":
_lock.withLock { _requests.telemetry.append(body) }
return (.ok, "application/json", Data("{}".utf8))
case "/api/v2/test/libraries/test-management/tests":
_lock.withLock { _requests.testManagement.append(body) }
return (.ok, "application/json", buildTestManagementResponse(requestId: extractRequestId(from: body)))
default:
return (.notFound, "application/json", Data("{}".utf8))
}
}
// MARK: - Response Builders
/// JSON:API requests echo their `data.id` back in the response. Pull it
/// out of the incoming body so each response carries the matching id —
/// the SDK rejects responses whose id doesn't match the request.
private func extractRequestId(from body: Data) -> String {
if let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any],
let data = json["data"] as? [String: Any],
let id = data["id"] as? String
{
return id
}
return "1"
}
private func buildSettingsResponse(requestId: String) -> Data {
let s = configuration.settings
let payload: [String: Any] = [
"data": [
"id": requestId,
"type": "ci_app_tracers_test_service_settings",
"attributes": [
"itr_enabled": s.itrEnabled,
"code_coverage": s.codeCoverage,
"tests_skipping": s.testsSkipping,
"known_tests_enabled": s.knownTestsEnabled,
"require_git": s.requireGit,
"flaky_test_retries_enabled": s.flakyTestRetriesEnabled,
"early_flake_detection": [
"enabled": s.earlyFlakeDetection.enabled,
"slow_test_retries": s.earlyFlakeDetection.slowTestRetries,
"faulty_session_threshold": s.earlyFlakeDetection.faultySessionThreshold
] as [String: Any],
"test_management": [
"enabled": s.testManagement.enabled,
"attempt_to_fix_retries": s.testManagement.attemptToFixRetries
] as [String: Any],
"impacted_tests_enabled": s.impactedTestsEnabled
] as [String: Any]
] as [String: Any]
]
return (try? JSONSerialization.data(withJSONObject: payload)) ?? Data()
}
private func buildKnownTestsResponse(requestId: String) -> Data {
let knownTests = configuration.knownTests
let totalTests = knownTests.values.flatMap { $0.values }.flatMap { $0 }.count
let payload: [String: Any] = [
"data": [
"id": requestId,
"type": "ci_app_libraries_tests",
"attributes": [
"tests": knownTests,
"page_info": [
"cursor": NSNull(),
"size": totalTests,
"has_next": false
] as [String: Any]
] as [String: Any]
] as [String: Any]
]
return (try? JSONSerialization.data(withJSONObject: payload)) ?? Data()
}
private func buildSkippableTestsResponse() -> Data {
let dataArray: [[String: Any]] = configuration.skippableTests.enumerated().map { idx, test in
[
"type": "test",
"id": "\(idx + 1)",
"attributes": [
"name": test.name,
"suite": test.suite,
"parameters": NSNull(),
"configurations": NSNull()
] as [String: Any]
]
}
let payload: [String: Any] = [
"meta": ["correlation_id": configuration.skippableTestsCorrelationId],
"data": dataArray
]
return (try? JSONSerialization.data(withJSONObject: payload)) ?? Data()
}
private func buildTestManagementResponse(requestId: String) -> Data {
var modulesDict: [String: Any] = [:]
for (moduleName, suites) in configuration.testManagement {
var suitesDict: [String: Any] = [:]
for (suiteName, tests) in suites {
var testsDict: [String: Any] = [:]
for (testName, props) in tests {
testsDict[testName] = [
"properties": [
"disabled": props.disabled,
"quarantined": props.quarantined,
"attempt_to_fix": props.attemptToFix
] as [String: Any]
]
}
suitesDict[suiteName] = ["tests": testsDict]
}
modulesDict[moduleName] = ["suites": suitesDict]
}
let payload: [String: Any] = [
"data": [
"id": requestId,
"type": "ci_app_libraries_tests",
"attributes": ["modules": modulesDict]
] as [String: Any]
]
return (try? JSONSerialization.data(withJSONObject: payload)) ?? Data()
}
// MARK: - Coverage Multipart Parser
/// Extracts the "coverage" field from a multipart/form-data request and decodes it.
private func parseCoveragePayload(headers: HTTPTestRequest.Headers, rawBody: Data) -> CoveragePayload? {
guard let contentType = headers.first(name: "content-type"),
contentType.lowercased().contains("multipart/form-data"),
let boundaryRange = contentType.range(of: "boundary=", options: .caseInsensitive)
else { return nil }
// Boundary may be quoted or unquoted; strip trailing parameters after ";"
var boundary = String(contentType[boundaryRange.upperBound...])
.components(separatedBy: ";").first ?? ""
boundary = boundary.trimmingCharacters(in: .whitespaces)
if boundary.hasPrefix("\"") && boundary.hasSuffix("\"") {
boundary = String(boundary.dropFirst().dropLast())
}
guard !boundary.isEmpty else { return nil }
guard let json = extractMultipartField(named: "coverage", from: rawBody, boundary: boundary)
else { return nil }
return try? JSONDecoder().decode(CoveragePayload.self, from: json)
}
/// Scans a raw multipart body and returns the data for the named field.
private func extractMultipartField(named fieldName: String, from body: Data, boundary: String) -> Data? {
guard let partDelim = ("--" + boundary + "\r\n").data(using: .utf8),
let headerBodySep = "\r\n\r\n".data(using: .utf8),
let bodyEndMark = ("\r\n--" + boundary).data(using: .utf8)
else { return nil }
var pos = body.startIndex
while pos < body.endIndex {
guard let delimRange = body.range(of: partDelim, in: pos..<body.endIndex) else { break }
let headersStart = delimRange.upperBound
guard let sepRange = body.range(of: headerBodySep, in: headersStart..<body.endIndex) else { break }
let headerBytes = body.subdata(in: headersStart..<sepRange.lowerBound)
guard let headerStr = String(data: headerBytes, encoding: .utf8) else {
pos = sepRange.upperBound; continue
}
let isTarget = headerStr.components(separatedBy: "\r\n").contains { line in
let l = line.lowercased()
return l.contains("content-disposition") && l.contains("name=\"\(fieldName)\"")
}
let bodyStart = sepRange.upperBound
let bodyEnd: Data.Index
if let endRange = body.range(of: bodyEndMark, in: bodyStart..<body.endIndex) {
bodyEnd = endRange.lowerBound
} else {
bodyEnd = body.endIndex
}
if isTarget { return body.subdata(in: bodyStart..<bodyEnd) }
pos = bodyEnd
}
return nil
}
}
// MARK: - Decoded Span Types
extension MockBackend {
/// Top-level envelope sent to /api/v2/citestcycle.
public struct SpanEnvelope: Decodable, Sendable {
public let version: Int
public let metadata: [String: [String: String]]
public let events: [SpanEvent]
var extended: [SpanEvent] { events.map { $0.extend(metadata: metadata) } }
/// All span payloads from all events.
public var allSpans: [Span] { extended.compactMap(\.span) }
/// Only events with type == "span"
public var infoSpans: [Span] { extended.filter { $0.isSpan }.compactMap(\.span) }
/// Only events with type == "test".
public var testSpans: [Span] { extended.filter { $0.isTest }.compactMap(\.span) }
/// Only end events
public var allEndEvents: [TestSpan] { extended.filter { $0.isEndEvent }.compactMap(\.event) }
/// Only suite_end events
public var suiteEndEvents: [TestSpan] { extended.filter { $0.isSuiteEndEvent }.compactMap(\.event) }
/// Only module_end events
public var moduleEndEvents: [TestSpan] { extended.filter { $0.isModuleEndEvent }.compactMap(\.event) }
/// Only session_end events
public var sessionEndEvents: [TestSpan] { extended.filter { $0.isSessionEndEvent }.compactMap(\.event) }
}
public enum SpanEvent: Decodable, Sendable {
case span(Span)
case test(Span)
case suiteEnd(TestSpan)
case moduleEnd(TestSpan)
case sessionEnd(TestSpan)
var isTest: Bool {
switch self {
case .test: return true
default: return false
}
}
var isSpan: Bool {
switch self {
case .span: return true
default: return false
}
}
var isEndEvent: Bool {
switch self {
case .moduleEnd, .suiteEnd, .sessionEnd: return true
default: return false
}
}
var isSuiteEndEvent: Bool {
switch self {
case .suiteEnd: return true
default: return false
}
}
var isModuleEndEvent: Bool {
switch self {
case .moduleEnd: return true
default: return false
}
}
var isSessionEndEvent: Bool {
switch self {
case .sessionEnd: return true
default: return false
}
}
var span: Span? {
switch self {
case .span(let span), .test(let span): return span
default: return nil
}
}
var event: TestSpan? {
switch self {
case .moduleEnd(let event), .suiteEnd(let event), .sessionEnd(let event): return event
default: return nil
}
}
struct Wrapper<T: Decodable>: Decodable {
let type: String
let version: Int
let content: T
}
struct Header: Decodable {
let type: String
let version: Int
}
enum CodingKeys: String, CodingKey {
case span
case test
case suiteEnd = "test_suite_end"
case moduleEnd = "test_module_end"
case sessionEnd = "test_session_end"
}
public init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
let header = try container.decode(Header.self)
guard let type = CodingKeys(rawValue: header.type) else {
throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath,
debugDescription: "Unknown type: \(header.type)"))
}
switch type {
case .span:
let envelope = try container.decode(Wrapper<Span>.self)
guard envelope.version == 1 else {
throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath,
debugDescription: "Unsupported version: \(envelope.version)"))
}
self = .span(envelope.content)
case .test:
let envelope = try container.decode(Wrapper<Span>.self)
guard envelope.version == 2 else {
throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath,
debugDescription: "Unsupported version: \(envelope.version)"))
}
self = .test(envelope.content)
case .suiteEnd:
let envelope = try container.decode(Wrapper<TestSpan>.self)
guard envelope.version == 1 else {
throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath,
debugDescription: "Unsupported version: \(envelope.version)"))
}
self = .suiteEnd(envelope.content)
case .moduleEnd:
let envelope = try container.decode(Wrapper<TestSpan>.self)
guard envelope.version == 1 else {
throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath,
debugDescription: "Unsupported version: \(envelope.version)"))
}
self = .moduleEnd(envelope.content)
case .sessionEnd:
let envelope = try container.decode(Wrapper<TestSpan>.self)
guard envelope.version == 1 else {
throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath,
debugDescription: "Unsupported version: \(envelope.version)"))
}
self = .sessionEnd(envelope.content)
}
}
func extend(metadata: borrowing [String: [String: String]]) -> Self {
switch self {
case .span(let span): return .span(span.extend(metadata: metadata, includeTestLevels: false))
case .test(let span): return .test(span.extend(metadata: metadata, includeTestLevels: true))
case .suiteEnd(let event): return .suiteEnd(event.extend(type: CodingKeys.suiteEnd.rawValue,
metadata: metadata))
case .moduleEnd(let event): return .moduleEnd(event.extend(type: CodingKeys.moduleEnd.rawValue,
metadata: metadata))
case .sessionEnd(let event): return .sessionEnd(event.extend(type: CodingKeys.sessionEnd.rawValue,
metadata: metadata))
}
}
}
public struct Span: Decodable, Sendable {
public let traceId: UInt64
public let spanId: UInt64
public let parentId: UInt64
public let testSessionId: UInt64?
public let testModuleId: UInt64?
public let testSuiteId: UInt64?
public let name: String
public let service: String
public let resource: String
public let type: String
public let start: UInt64
public let duration: UInt64
public let error: Int
public let meta: [String: String]
public let metrics: [String: Double]
public let itrCorrelationId: String?
enum CodingKeys: String, CodingKey {
case traceId = "trace_id"
case spanId = "span_id"
case parentId = "parent_id"
case testSessionId = "test_session_id"
case testModuleId = "test_module_id"
case testSuiteId = "test_suite_id"
case name, service, resource, type, start, duration, error, meta, metrics
case itrCorrelationId = "itr_correlation_id"
}
func extend(metadata: borrowing [String: [String: String]], includeTestLevels: Bool) -> Self {
// Priority (highest to lowest): span.meta > metadata[type] > metadata["test_levels"] > metadata["*"]
// "test_levels" only applies to test* spans, not generic "span" events.
// Build from lowest priority up; { a, _ in a } keeps the already-accumulated value.
var meta = [String: String]()
if let common = metadata["*"] { meta.merge(common) { a, _ in a } }
if includeTestLevels, let levels = metadata["test_levels"] { meta.merge(levels) { a, _ in a } }
if let typed = metadata[type] { meta.merge(typed) { a, _ in a } }
meta.merge(self.meta) { a, _ in a }
return .init(traceId: traceId, spanId: spanId, parentId: parentId,
testSessionId: testSessionId, testModuleId: testModuleId,
testSuiteId: testSuiteId, name: name, service: service,
resource: resource, type: type, start: start, duration: duration,
error: error, meta: meta, metrics: metrics, itrCorrelationId: itrCorrelationId)
}
}
public struct TestSpan: Decodable, Sendable {
public let testSessionId: UInt64
public let testModuleId: UInt64?
public let testSuiteId: UInt64?
public let name: String
public let service: String
public let resource: String
public let start: UInt64
public let duration: UInt64
public let error: Int
public let meta: [String: String]
public let metrics: [String: Double]
enum CodingKeys: String, CodingKey {
case testSessionId = "test_session_id"
case testModuleId = "test_module_id"
case testSuiteId = "test_suite_id"
case name, service, resource, start, duration, error, meta, metrics
}
func extend(type: String, metadata: borrowing [String: [String: String]]) -> Self {
// Priority (highest to lowest): span.meta > metadata[type] > metadata["test_levels"] > metadata["*"]
var meta = [String: String]()
if let common = metadata["*"] { meta.merge(common) { a, _ in a } }
if let levels = metadata["test_levels"] { meta.merge(levels) { a, _ in a } }
if let typed = metadata[type] { meta.merge(typed) { a, _ in a } }
meta.merge(self.meta) { a, _ in a }
return .init(testSessionId: testSessionId, testModuleId: testModuleId,
testSuiteId: testSuiteId, name: name, service: service,
resource: resource, start: start, duration: duration,
error: error, meta: meta, metrics: metrics)
}
}
}
// MARK: - Decoded Coverage Types
extension MockBackend {
/// Top-level payload received at /api/v2/citestcov (extracted from the "coverage" multipart field).
public struct CoveragePayload: Decodable, Sendable {
public let version: Int
public let coverages: [TestCoverage]
}
/// Per-test coverage entry within a payload.
public struct TestCoverage: Decodable, Sendable {
public let testSessionId: UInt64
public let testSuiteId: UInt64
public let spanId: UInt64
public let files: [CoverageFile]
enum CodingKeys: String, CodingKey {
case testSessionId = "test_session_id"
case testSuiteId = "test_suite_id"
case spanId = "span_id"
case files
}
}
/// A covered-file entry. `bitmap` is a bit-per-line coverage mask, base64-decoded from JSON.
public struct CoverageFile: Decodable, Sendable {
public let filename: String
public let bitmap: Data
/// Returns the set of 1-based line numbers that are marked as covered in the bitmap.
public var coveredLines: IndexSet {
var result = IndexSet()
for (byteIdx, byte) in bitmap.enumerated() {
for bit in 0..<8 {
if byte & (1 << (7 - bit)) != 0 {
result.insert(byteIdx * 8 + bit + 1)
}
}
}
return result
}
}
}
// MARK: - Decoded Log Types
extension MockBackend {
/// A single log entry received at /api/v2/logs.
public struct Log: Decodable, Sendable {
public let fields: [String: JSONValue]
public subscript(key: String) -> JSONValue? { fields[key] }
public var message: String? { fields["message"]?.stringValue }
public var status: String? { fields["status"]?.stringValue }
public var service: String? { fields["service"]?.stringValue }
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: _DynamicKey.self)
var fields: [String: JSONValue] = [:]
for key in container.allKeys {
fields[key.stringValue] = (try? container.decode(JSONValue.self, forKey: key)) ?? .null
}
self.fields = fields
}
}
/// A flexible JSON value used in log fields.
public enum JSONValue: Decodable, Sendable, CustomStringConvertible {
case string(String)
case number(Double)
case bool(Bool)
case null
public init(from decoder: Decoder) throws {
let c = try decoder.singleValueContainer()
// Bool must be checked before Double since Bool is a subtype in some decoders
if let v = try? c.decode(Bool.self) { self = .bool(v); return }
if let v = try? c.decode(Double.self) { self = .number(v); return }
if let v = try? c.decode(String.self) { self = .string(v); return }
self = .null
}
public var stringValue: String? { if case .string(let v) = self { return v }; return nil }
public var numberValue: Double? { if case .number(let v) = self { return v }; return nil }
public var boolValue: Bool? { if case .bool(let v) = self { return v }; return nil }
public var description: String {
switch self {
case .string(let v): return v
case .number(let v): return "\(v)"
case .bool(let v): return "\(v)"
case .null: return "null"
}
}
}
}
// MARK: - Telemetry parsing
extension MockBackend {
/// A decoded telemetry metric/distribution series.
public struct TelemetrySeries: Sendable, Equatable {
public let metric: String
/// `count` / `gauge` / `rate` for `generate-metrics`; `nil` for distributions.
public let type: String?
public let tags: [String]
/// Sample values: the value of each `[timestamp, value]` point for
/// `generate-metrics`, or the raw samples for `distributions`.
public let points: [Double]
}
/// Result of decoding the raw telemetry batches captured by the backend.
public struct ParsedTelemetry: Sendable {
public let metrics: [TelemetrySeries]
public let distributions: [TelemetrySeries]
/// Every telemetry request type seen (`app-started`, `generate-metrics`,
/// `distributions`, `app-heartbeat`, `app-closing`, …).
public let events: Set<String>
}
/// Decode the raw `/api/v2/apmtelemetry` bodies into typed series and event
/// types. Handles both the direct single-payload form (e.g. `app-started`)
/// and the `message-batch` envelope used for metrics/heartbeats/closing.
public static func parseTelemetry(_ batches: [Data]) -> ParsedTelemetry {
var metrics: [TelemetrySeries] = []
var distributions: [TelemetrySeries] = []
var events: Set<String> = []
func number(_ any: Any?) -> Double? { (any as? NSNumber)?.doubleValue }
func series(from dict: [String: Any], distribution: Bool) -> TelemetrySeries? {
guard let metric = dict["metric"] as? String else { return nil }
let tags = dict["tags"] as? [String] ?? []
let type = dict["type"] as? String
var points: [Double] = []
if distribution {
points = (dict["points"] as? [Any])?.compactMap(number) ?? []
} else if let pairs = dict["points"] as? [[Any]] {
// generate-metrics points are [timestamp, value] pairs.
points = pairs.compactMap { $0.count >= 2 ? number($0[1]) : nil }
}
return TelemetrySeries(metric: metric, type: type, tags: tags, points: points)
}
func handle(requestType: String, payload: Any?) {
events.insert(requestType)
switch requestType {
case "message-batch":
for msg in (payload as? [[String: Any]]) ?? [] {
handle(requestType: msg["request_type"] as? String ?? "",
payload: msg["payload"])
}
case "generate-metrics":
for s in (payload as? [String: Any])?["series"] as? [[String: Any]] ?? [] {
if let series = series(from: s, distribution: false) { metrics.append(series) }
}
case "distributions":
for s in (payload as? [String: Any])?["series"] as? [[String: Any]] ?? [] {
if let series = series(from: s, distribution: true) { distributions.append(series) }
}
default:
break
}
}
for data in batches {
guard let top = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let requestType = top["request_type"] as? String
else { continue }
handle(requestType: requestType, payload: top["payload"])
}
return ParsedTelemetry(metrics: metrics, distributions: distributions, events: events)
}
}
// MARK: - Mock Configuration Types
extension MockBackend {
/// Configure the settings response returned to the SDK.
public struct Settings: Sendable {
public var itrEnabled: Bool
public var codeCoverage: Bool
public var testsSkipping: Bool
public var knownTestsEnabled: Bool
public var requireGit: Bool
public var flakyTestRetriesEnabled: Bool
public var earlyFlakeDetection: EFDConfig
public var testManagement: TestManagementConfig
public var impactedTestsEnabled: Bool
public init(
itrEnabled: Bool = false, codeCoverage: Bool = false, testsSkipping: Bool = false,
knownTestsEnabled: Bool = false, requireGit: Bool = false, flakyTestRetriesEnabled: Bool = false,
earlyFlakeDetection: EFDConfig = .init(), testManagement: TestManagementConfig = .init(),
impactedTestsEnabled: Bool = false
) {
self.itrEnabled = itrEnabled; self.codeCoverage = codeCoverage
self.testsSkipping = testsSkipping; self.knownTestsEnabled = knownTestsEnabled
self.requireGit = requireGit; self.flakyTestRetriesEnabled = flakyTestRetriesEnabled
self.earlyFlakeDetection = earlyFlakeDetection; self.testManagement = testManagement
self.impactedTestsEnabled = impactedTestsEnabled
}
}
/// Early Flake Detection configuration returned in settings.
public struct EFDConfig: Sendable {
public var enabled: Bool
public var slowTestRetries: [String: UInt] // e.g. ["5s": 3, "1m": 1]
public var faultySessionThreshold: Double
public init(enabled: Bool = false, slowTestRetries: [String: UInt] = [:],
faultySessionThreshold: Double = 1.0) {
self.enabled = enabled; self.slowTestRetries = slowTestRetries
self.faultySessionThreshold = faultySessionThreshold
}
}
/// Test Management configuration returned in settings.
public struct TestManagementConfig: Sendable {
public var enabled: Bool
public var attemptToFixRetries: UInt
public init(enabled: Bool = false, attemptToFixRetries: UInt = 0) {
self.enabled = enabled; self.attemptToFixRetries = attemptToFixRetries
}
}
/// Module → Suite → [TestName]. Used for Known Tests response.
public typealias KnownTestsMap = [String: [String: [String]]]
/// A single test to be skipped in ITR response.
public struct SkippableTest: Sendable {
public let name: String
public let suite: String
public init(name: String, suite: String) { self.name = name; self.suite = suite }
}
/// Module → Suite → TestName → Properties. Used for Test Management response.
public typealias TestManagementMap = [String: [String: [String: MockTestProperties]]]
public struct MockTestProperties: Sendable {
public var disabled: Bool
public var quarantined: Bool
public var attemptToFix: Bool
public init(disabled: Bool = false, quarantined: Bool = false, attemptToFix: Bool = false) {
self.disabled = disabled; self.quarantined = quarantined; self.attemptToFix = attemptToFix
}
}
}
// MARK: - Private: ZLIB Decompression (mirrors DataCompression.swift's deflate encoding)
private extension Data {
var _zlibInflated: Data? {
guard !isEmpty else { return self }
return withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Data? in
guard let src = ptr.bindMemory(to: UInt8.self).baseAddress else { return nil }
var destCapacity = Swift.max(count * 4, 1024)
while destCapacity <= count * 64 {
var dest = [UInt8](repeating: 0, count: destCapacity)
let decoded = compression_decode_buffer(&dest, destCapacity, src, count, nil, COMPRESSION_ZLIB)
if decoded > 0 { return Data(bytes: dest, count: decoded) }
destCapacity *= 2
}
return nil
}
}
}
// MARK: - Private: Dynamic CodingKey for MockLog
private struct _DynamicKey: CodingKey {
let stringValue: String
let intValue: Int? = nil
init?(stringValue: String) { self.stringValue = stringValue }
init?(intValue: Int) { return nil }
}