-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathTestUtilities.swift
185 lines (159 loc) · 6.58 KB
/
TestUtilities.swift
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftOpenAPIGenerator open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import Foundation
import Yams
import OpenAPIKit
@testable import _OpenAPIGeneratorCore
class Test_Core: XCTestCase {
/// Setup method called before the invocation of each test method in the class.
override func setUp() async throws {
try await super.setUp()
continueAfterFailure = false
}
func makeTranslator(
components: OpenAPI.Components = .noComponents,
diagnostics: any DiagnosticCollector = PrintingDiagnosticCollector(),
featureFlags: FeatureFlags = [.uuidSupport]
) -> TypesFileTranslator {
makeTypesTranslator(components: components, diagnostics: diagnostics, featureFlags: featureFlags)
}
func makeTypesTranslator(
components: OpenAPI.Components = .noComponents,
diagnostics: any DiagnosticCollector = PrintingDiagnosticCollector(),
featureFlags: FeatureFlags = []
) -> TypesFileTranslator {
TypesFileTranslator(
config: makeConfig(featureFlags: featureFlags),
diagnostics: diagnostics,
components: components
)
}
func makeConfig(featureFlags: FeatureFlags = []) -> Config {
.init(mode: .types, access: Config.defaultAccessModifier, featureFlags: featureFlags)
}
func loadSchemaFromYAML(_ yamlString: String) throws -> JSONSchema {
try YAMLDecoder().decode(JSONSchema.self, from: yamlString)
}
static var testTypeName: TypeName { .init(swiftKeyPath: ["Foo"]) }
var typeAssigner: TypeAssigner { makeTranslator().typeAssigner }
var typeMatcher: TypeMatcher { makeTranslator().typeMatcher }
var context: TranslatorContext { makeTranslator().context }
var asSwiftSafeName: (String) -> String { context.asSwiftSafeName }
func makeProperty(originalName: String, typeUsage: TypeUsage) -> PropertyBlueprint {
.init(originalName: originalName, typeUsage: typeUsage, context: context)
}
}
func XCTAssertEqualCodable<T>(
_ expression1: @autoclosure () throws -> T,
_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) where T: Equatable & Encodable {
let value1: T
let value2: T
do {
value1 = try expression1()
value2 = try expression2()
} catch {
XCTFail(
"XCTAssertEqualCodable expression evaluation threw an error: \(error.localizedDescription)",
file: file,
line: line
)
return
}
// If objects aren't equal, convert both into Yaml and diff them in that representation
if value1 == value2 { return }
let encoder = YAMLEncoder()
encoder.options.sortKeys = true
let data1: String
let data2: String
do {
data1 = try encoder.encode(value1)
data2 = try encoder.encode(value2)
} catch {
XCTFail(
"XCTAssertEqualCodable encoding to Yaml threw an error: \(error.localizedDescription)",
file: file,
line: line
)
return
}
var messageLines: [String] = ["XCTAssertEqualCodable failed, values are not equal"]
messageLines.append("=== Value 1 ===:\n\(data1.withLineNumberPrefixes)")
messageLines.append("=== Value 2 ===:\n\(data2.withLineNumberPrefixes)")
messageLines.append("=== Diff ===")
let lines1 = data1.split(separator: "\n")
let lines2 = data2.split(separator: "\n")
for i in 0..<max(lines1.count, lines2.count) {
if i < lines1.endIndex && i < lines2.endIndex {
if lines1[i] == lines2[i] {
continue
} else {
messageLines.append("First difference found at line \(i+1)")
messageLines.append("< \(lines1[i])")
messageLines.append("> \(lines2[i])")
}
} else {
// We hit the end of one of the sequences
messageLines.append("First difference found at line \(i+1)")
if i == lines1.endIndex {
messageLines.append("< [END OF FILE]")
messageLines.append("> \(lines2[2])")
} else {
messageLines.append("< \(lines1[i])")
messageLines.append("> [END OF FILE]")
}
}
break
}
XCTFail(messageLines.joined(separator: "\n"), file: file, line: line)
}
func XCTAssertUnsortedEqual<T>(
_ expression1: @autoclosure () throws -> [T],
_ expression2: @autoclosure () throws -> [T],
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) where T: Comparable {
XCTAssertEqual(try expression1().sorted(), try expression2().sorted(), message(), file: file, line: line)
}
/// Both names must have the same number of components, throws otherwise.
func newTypeName(swiftFQName: String, jsonFQName: String) throws -> TypeName {
var jsonComponents = jsonFQName.split(separator: "/").map(String.init)
let swiftComponents = swiftFQName.split(separator: ".").map(String.init)
guard !jsonComponents.isEmpty else { throw TypeCreationError(swift: swiftFQName, json: jsonFQName) }
let hadJSONRoot = jsonComponents[0] == "#"
if hadJSONRoot { jsonComponents.removeFirst() }
struct TypeCreationError: Error, CustomStringConvertible, LocalizedError {
var swift: String
var json: String
var description: String { "swift: \(swift), json: \(json)" }
var errorDescription: String? { description }
}
guard swiftComponents.count == jsonComponents.count else {
throw TypeCreationError(swift: swiftFQName, json: jsonFQName)
}
let jsonRoot: [TypeName.Component]
if hadJSONRoot { jsonRoot = [.init(swift: nil, json: "#")] } else { jsonRoot = [] }
return .init(components: jsonRoot + zip(swiftComponents, jsonComponents).map(TypeName.Component.init))
}
/// A diagnostic collector that accumulates all received diagnostics into
/// an array.
final class AccumulatingDiagnosticCollector: DiagnosticCollector {
private(set) var diagnostics: [Diagnostic] = []
func emit(_ diagnostic: Diagnostic) { diagnostics.append(diagnostic) }
}