-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathABI.EncodedTest.swift
More file actions
320 lines (282 loc) · 10.5 KB
/
ABI.EncodedTest.swift
File metadata and controls
320 lines (282 loc) · 10.5 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
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024-2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//
extension ABI {
/// A type implementing the JSON encoding of ``Test`` for the ABI entry point
/// and event stream output.
///
/// The properties and members of this type are documented in ABI/JSON.md.
///
/// You can use this type and its conformance to [`Codable`](https://developer.apple.com/documentation/swift/codable),
/// when integrating the testing library with development tools. It is not
/// part of the testing library's public interface.
public struct EncodedTest<V>: Sendable where V: ABI.Version {
/// An enumeration describing the various kinds of test.
enum Kind: String, Sendable {
/// A test suite.
case suite
/// A test function.
case function
}
/// The kind of test.
var kind: Kind
/// The programmatic name of the test, such as its corresponding Swift
/// function or type name.
var name: String
/// The developer-supplied human-readable name of the test.
var displayName: String?
/// The source location of this test.
var sourceLocation: EncodedSourceLocation<V>
/// A type implementing the JSON encoding of ``Test/ID`` for the ABI entry
/// point and event stream output.
struct ID: Codable {
/// The string value representing the corresponding test ID.
var stringValue: String
init(encoding testID: borrowing Test.ID) {
stringValue = String(describing: copy testID)
}
func encode(to encoder: any Encoder) throws {
try stringValue.encode(to: encoder)
}
init(from decoder: any Decoder) throws {
stringValue = try String(from: decoder)
}
}
/// The unique identifier of this test.
var id: ID
/// The test cases in this test, if it is a parameterized test function.
///
/// - Warning: Test cases are not yet part of the JSON schema.
var _testCases: [EncodedTestCase<V>]?
/// Whether or not the test is parameterized.
///
/// If this instance represents a test _suite_, the value of this property
/// is `nil`.
var isParameterized: Bool?
/// A type describing a parameter to a parameterized test function.
///
/// - Warning: Parameter info is not yet part of the JSON schema.
struct Parameter: Sendable, Codable {
/// The name of the parameter, if known.
var name: String?
/// The fully-qualified name of the parameter's type.
var typeName: String
}
/// Information about the parameters to this test.
///
/// If this instance does not represent a _parameterized test function_, the
/// value of this property is `nil`.
///
/// - Warning: Parameter info is not yet part of the JSON schema.
var _parameters: [Parameter]?
/// An equivalent of ``tags`` that preserves ABIv6.3 support.
var _tags: [String]?
/// The tags associated with the test.
///
/// @Metadata {
/// @Available(Swift, introduced: 6.4)
/// }
var tags: [String]?
/// The bugs associated with the test.
///
/// @Metadata {
/// @Available(Swift, introduced: 6.4)
/// }
var bugs: [Bug]?
/// The time limits associated with the test.
///
/// @Metadata {
/// @Available(Swift, introduced: 6.4)
/// }
var timeLimit: Double?
}
}
extension ABI {
/// A type implementing the JSON encoding of ``Test/Case`` for the ABI entry
/// point and event stream output.
///
/// The properties and members of this type are documented in ABI/JSON.md.
///
/// This type is not part of the public interface of the testing library. It
/// assists in converting values to JSON; clients that consume this JSON are
/// expected to write their own decoders.
///
/// - Warning: Test cases are not yet part of the JSON schema.
struct EncodedTestCase<V>: Sendable where V: ABI.Version {
var id: String
var displayName: String
init(encoding testCase: borrowing Test.Case) {
guard let arguments = testCase.arguments else {
preconditionFailure(reportBugMessage("Attempted to initialize an EncodedTestCase encoding a test case which is not parameterized: \(testCase)."))
}
// TODO: define an encodable form of Test.Case.ID
id = String(describing: testCase.id)
displayName = arguments.lazy
.map(\.value)
.map(String.init(describingForTest:))
.joined(separator: ", ")
}
}
}
// MARK: - Codable
extension ABI.EncodedTest: Codable {}
extension ABI.EncodedTest.Kind: Codable {}
extension ABI.EncodedTestCase: Codable {}
// MARK: - Conversion to/from library types
extension ABI.EncodedTest {
/// Initialize an instance of this type from the given value.
///
/// - Parameters:
/// - test: The test to initialize this instance from.
public init(encoding test: borrowing Test) {
if test.isSuite {
kind = .suite
} else {
kind = .function
isParameterized = test.isParameterized
}
name = test.name
displayName = test.displayName
sourceLocation = ABI.EncodedSourceLocation(encoding: test.sourceLocation)
id = ID(encoding: test.id)
// Experimental fields
if V.includesExperimentalFields {
if isParameterized == true {
_testCases = test.uncheckedTestCases?.map(ABI.EncodedTestCase.init(encoding:))
_parameters = test.parameters?.map { parameter in
Parameter(
name: parameter.secondName ?? parameter.firstName,
typeName: parameter.typeInfo.fullyQualifiedName
)
}
}
let tags = test.tags
if !tags.isEmpty {
self._tags = tags.map(String.init(describing:))
}
}
if V.versionNumber >= ABI.v6_4.versionNumber {
self.tags = test.tags.sorted().map { tag in
switch tag.kind {
case .staticMember(let value): value
}
}
let bugs = test.associatedBugs
if !bugs.isEmpty {
self.bugs = bugs
}
self.timeLimit = test.timeLimit.map { $0 / .seconds(1) }
}
}
}
@_spi(ForToolsIntegrationOnly)
extension Test {
/// Attempt to reconstruct an instance of ``TypeInfo`` from an encoded test.
///
/// - Parameters:
/// - test: The test that may contain type information.
///
/// - Returns: On success, an instance of ``TypeInfo`` describing the suite
/// type containing or equalling `test`. On failure, `nil`.
private static func _makeTypeInfo<V>(for test: ABI.EncodedTest<V>) -> TypeInfo? {
// Find the module name, which for XCTest compatibility is split from the
// rest of the test ID by a period character instead of a slash character.
let testID = test.id.stringValue
let splitByPeriod = rawIdentifierAwareSplit(testID, separator: ".", maxSplits: 1)
var testIDComponents = rawIdentifierAwareSplit(testID, separator: "/")
guard let moduleName = splitByPeriod.first,
let firstComponent = testIDComponents.first,
moduleName.endIndex < firstComponent.endIndex else {
// The string wasn't structured as expected for a Swift Testing or XCTest
// test ID.
return nil
}
// Replace the first component string, which is currently shaped like
// "ModuleName.TypeName", with ["ModuleName", "TypeName"]
let secondTestIDComponent = testID[moduleName.endIndex ..< firstComponent.endIndex].dropFirst()
testIDComponents[0] = moduleName
testIDComponents.insert(secondTestIDComponent, at: 1)
if test.kind == .function {
if let lastComponent = testIDComponents.last?.utf8,
lastComponent.first != UInt8(ascii: "`"),
lastComponent.contains(UInt8(ascii: ":")) {
// The last component of the test ID (when split by slash characters)
// appears to be a source location. Remove it as it's not part of the
// suite type.
testIDComponents.removeLast()
}
// The last component of the test ID is the name of the test function.
// Remove that too.
testIDComponents.removeLast()
}
// Recombine the module name with the rest of the test ID to produce the
// fully-qualified type name. Join everything by slashes.
return TypeInfo(fullyQualifiedNameComponents: testIDComponents.map(String.init))
}
/// Initialize an instance of this type from the given value.
///
/// - Parameters:
/// - test: The encoded test to initialize this instance from.
///
/// The resulting instance of ``Test`` cannot be run; attempting to do so will
/// throw an error.
public init?<V>(decoding test: ABI.EncodedTest<V>) {
let sourceLocation = SourceLocation(decoding: test.sourceLocation) ?? .unknown
let typeInfo = Self._makeTypeInfo(for: test)
// Construct the (partial) list of traits available in the encoded test.
// Note we do not try to encode _all_ traits because many trait types simply
// cannot be represented as JSON.
var traits = [any Trait]()
if let tags = test.tags ?? test._tags {
let tags = tags.map(Tag.init(userProvidedStringValue:))
traits.append(Tag.List(tags: tags))
}
if let bugs = test.bugs {
traits += bugs
}
if let timeLimit = test.timeLimit {
traits.append(TimeLimitTrait(timeLimit: .seconds(timeLimit)))
}
switch test.kind {
case .suite:
guard let typeInfo else {
return nil
}
self.init(
displayName: test.displayName,
traits: traits,
sourceLocation: sourceLocation,
containingTypeInfo: typeInfo,
isSynthesized: true
)
case .function:
let parameters = test._parameters.map { parameters in
parameters.enumerated().map { i, parameter in
Testing.Test.Parameter(
index: i,
firstName: parameter.name ?? "_",
typeInfo: TypeInfo(fullyQualifiedName: parameter.typeName, mangledName: nil)
)
}
}
self.init(
name: test.name,
displayName: test.displayName,
traits: traits,
sourceBounds: __SourceBounds(lowerBoundOnly: sourceLocation),
containingTypeInfo: typeInfo,
xcTestCompatibleSelector: nil,
testCases: { () -> Test.Case.Generator<CollectionOfOne<Void>> in
throw APIMisuseError(description: "This instance of 'Test' was synthesized at runtime and cannot be run directly.")
},
parameters: parameters ?? []
)
}
}
}