Skip to content

Commit 379b047

Browse files
authored
[NFC] Refactor PetstoreConsumerTests to allow multiple versions (#157)
[NFC] Refactor PetstoreConsumerTests to allow multiple versions ### Motivation In upcoming features that contain breaking changes, but we'll stage them in behind a feature flag, we'd like to have multiple variants of the `PetstoreConsumerTests` test target, allowing us to test both the existing behavior and the new behavior once a feature flag is enabled. These additional variants would be temporary, and would be deleted again (or rather, the main test suite would be updated) once the feature flag is enabled unconditionally. So the steady state number of `PetstoreConsumerTest` variants would continue to be 1, just for short periods of time, it might be higher. ### Modifications This PR makes that possible by refactoring common functionality into a new internal target `PetstoreConsumerTestCore`. Note that all the variants of the test target share the same OpenAPI document, but generate different variants of the reference code. Highlights: - new `PetstoreConsumerTestCore` target, depended on by the existing `PetstoreConsumerTests` - added an ability to _not_ fail the test when specific diagnostics are emitted (through the new `ignoredDiagnosticMessages: Set<String>` parameter), which allows us to test both existing and new behavior on the same OpenAPI document. Other, non-allowlisted diagnostics, still continue to fail the test, so new ones won't sneak through undetected. - many test functions now optionally take `featureFlags` and `ignoredDiagnosticMessages`, again allowing us to test both existing and proposed behavior hidden behind a feature flag ### Result It will be a lot easier to temporarily introduce other variants of the `PetstoreConsumerTests` test target to allow for thoroughly testing features even before they are enabled by default, giving us more confidence in the accuracy of proposals and their associated implementations. ### Test Plan All tests continue to pass, this is an NFC, a pure refactoring, making the next PR much smaller. To see how this all fits together, check out the PR that has all the changes: #146. That said, these partial PRs are easier to review, as they're each focused on one task. Reviewed by: gjcairo, simonjbeaumont Builds: ✔︎ pull request validation (5.8) - Build finished. ✔︎ pull request validation (5.9) - Build finished. ✔︎ pull request validation (docc test) - Build finished. ✔︎ pull request validation (integration test) - Build finished. ✔︎ pull request validation (nightly) - Build finished. ✔︎ pull request validation (soundness) - Build finished. #157
1 parent b1d310f commit 379b047

File tree

13 files changed

+209
-136
lines changed

13 files changed

+209
-136
lines changed

Package.swift

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,13 +123,22 @@ let package = Package(
123123
swiftSettings: swiftSettings
124124
),
125125

126+
// Common types for concrete PetstoreConsumer*Tests test targets.
127+
.target(
128+
name: "PetstoreConsumerTestCore",
129+
dependencies: [
130+
.product(name: "OpenAPIRuntime", package: "swift-openapi-runtime")
131+
],
132+
swiftSettings: swiftSettings
133+
),
134+
126135
// PetstoreConsumerTests
127136
// Builds and tests the reference code from GeneratorReferenceTests
128137
// to ensure it actually works correctly at runtime.
129138
.testTarget(
130139
name: "PetstoreConsumerTests",
131140
dependencies: [
132-
.product(name: "OpenAPIRuntime", package: "swift-openapi-runtime")
141+
"PetstoreConsumerTestCore"
133142
],
134143
swiftSettings: swiftSettings
135144
),
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the SwiftOpenAPIGenerator open source project
4+
//
5+
// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
import OpenAPIRuntime
15+
import Foundation
16+
17+
public enum TestError: Swift.Error, LocalizedError, CustomStringConvertible {
18+
case noHandlerFound(method: HTTPMethod, path: [RouterPathComponent])
19+
case invalidURLString(String)
20+
case unexpectedValue(Any)
21+
case unexpectedMissingRequestBody
22+
23+
public var description: String {
24+
switch self {
25+
case .noHandlerFound(let method, let path):
26+
return "No handler found for method \(method.name) and path \(path.stringPath)"
27+
case .invalidURLString(let string):
28+
return "Invalid URL string: \(string)"
29+
case .unexpectedValue(let value):
30+
return "Unexpected value: \(value)"
31+
case .unexpectedMissingRequestBody:
32+
return "Unexpected missing request body"
33+
}
34+
}
35+
36+
public var errorDescription: String? {
37+
description
38+
}
39+
}
40+
41+
public extension Date {
42+
static var test: Date {
43+
Date(timeIntervalSince1970: 1_674_036_251)
44+
}
45+
46+
static var testString: String {
47+
"2023-01-18T10:04:11Z"
48+
}
49+
}
50+
51+
public extension Array where Element == RouterPathComponent {
52+
var stringPath: String {
53+
map(\.description).joined(separator: "/")
54+
}
55+
}
56+
57+
public extension Response {
58+
init(
59+
statusCode: Int,
60+
headers: [HeaderField] = [],
61+
encodedBody: String
62+
) {
63+
self.init(
64+
statusCode: statusCode,
65+
headerFields: headers,
66+
body: Data(encodedBody.utf8)
67+
)
68+
}
69+
70+
static var listPetsSuccess: Self {
71+
.init(
72+
statusCode: 200,
73+
headers: [
74+
.init(name: "content-type", value: "application/json")
75+
],
76+
encodedBody: #"""
77+
[
78+
{
79+
"id": 1,
80+
"name": "Fluffz"
81+
}
82+
]
83+
"""#
84+
)
85+
}
86+
}
87+
88+
public extension Data {
89+
var pretty: String {
90+
String(decoding: self, as: UTF8.self)
91+
}
92+
93+
static var abcdString: String {
94+
"abcd"
95+
}
96+
97+
static var abcd: Data {
98+
Data(abcdString.utf8)
99+
}
100+
101+
static var efghString: String {
102+
"efgh"
103+
}
104+
105+
static var quotedEfghString: String {
106+
#""efgh""#
107+
}
108+
109+
static var efgh: Data {
110+
Data(efghString.utf8)
111+
}
112+
}
113+
114+
public extension Request {
115+
init(
116+
path: String,
117+
query: String? = nil,
118+
method: HTTPMethod,
119+
headerFields: [HeaderField] = [],
120+
encodedBody: String
121+
) throws {
122+
let body = Data(encodedBody.utf8)
123+
self.init(
124+
path: path,
125+
query: query,
126+
method: method,
127+
headerFields: headerFields,
128+
body: body
129+
)
130+
}
131+
}

Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class FileBasedReferenceTests: XCTestCase {
4545
}
4646

4747
func testPetstore() throws {
48-
try _test(referenceProjectNamed: .petstore)
48+
try _test(referenceProject: .init(name: .petstore))
4949
}
5050

5151
// MARK: - Private
@@ -60,7 +60,8 @@ class FileBasedReferenceTests: XCTestCase {
6060
}
6161

6262
func performReferenceTest(
63-
_ referenceTest: TestConfig
63+
_ referenceTest: TestConfig,
64+
ignoredDiagnosticMessages: Set<String> = []
6465
) throws {
6566
print(
6667
"""
@@ -85,7 +86,8 @@ class FileBasedReferenceTests: XCTestCase {
8586

8687
// Run the requested generator invocation
8788
let generatorPipeline = self.makeGeneratorPipeline(
88-
config: referenceTest.asConfig
89+
config: referenceTest.asConfig,
90+
ignoredDiagnosticMessages: ignoredDiagnosticMessages
8991
)
9092
let generatedOutputSource = try generatorPipeline.run(input)
9193

@@ -115,16 +117,33 @@ class FileBasedReferenceTests: XCTestCase {
115117
enum ReferenceProjectName: String, Hashable, CaseIterable {
116118
case petstore
117119

118-
var fileName: String {
120+
var openAPIDocFileName: String {
119121
"\(rawValue).yaml"
120122
}
121123

122-
var directoryName: String {
124+
var fixtureCodeDirectoryName: String {
123125
rawValue.capitalized
124126
}
125127
}
126128

127-
func _test(referenceProjectNamed name: ReferenceProjectName) throws {
129+
struct ReferenceProject: Hashable, Equatable {
130+
var name: ReferenceProjectName
131+
var customDirectoryName: String? = nil
132+
133+
var fixtureCodeDirectoryName: String {
134+
customDirectoryName ?? name.fixtureCodeDirectoryName
135+
}
136+
137+
var openAPIDocFileName: String {
138+
name.openAPIDocFileName
139+
}
140+
}
141+
142+
func _test(
143+
referenceProject project: ReferenceProject,
144+
featureFlags: FeatureFlags = [],
145+
ignoredDiagnosticMessages: Set<String> = []
146+
) throws {
128147
let modes: [GeneratorMode] = [
129148
.types,
130149
.client,
@@ -133,19 +152,23 @@ class FileBasedReferenceTests: XCTestCase {
133152
for mode in modes {
134153
try performReferenceTest(
135154
.init(
136-
docFilePath: "Docs/\(name.fileName)",
155+
docFilePath: "Docs/\(project.openAPIDocFileName)",
137156
mode: mode,
138157
additionalImports: [],
139-
featureFlags: [],
140-
referenceOutputDirectory: "ReferenceSources/\(name.directoryName)"
141-
)
158+
featureFlags: featureFlags,
159+
referenceOutputDirectory: "ReferenceSources/\(project.fixtureCodeDirectoryName)"
160+
),
161+
ignoredDiagnosticMessages: ignoredDiagnosticMessages
142162
)
143163
}
144164
}
145165
}
146166

147167
extension FileBasedReferenceTests {
148-
private func makeGeneratorPipeline(config: Config) -> GeneratorPipeline {
168+
private func makeGeneratorPipeline(
169+
config: Config,
170+
ignoredDiagnosticMessages: Set<String> = []
171+
) -> GeneratorPipeline {
149172
let parser = YamsParser()
150173
let translator = MultiplexTranslator()
151174
let renderer = TextBasedRenderer()
@@ -160,7 +183,10 @@ extension FileBasedReferenceTests {
160183
return newFile
161184
},
162185
config: config,
163-
diagnostics: XCTestDiagnosticCollector(test: self)
186+
diagnostics: XCTestDiagnosticCollector(
187+
test: self,
188+
ignoredDiagnosticMessages: ignoredDiagnosticMessages
189+
)
164190
)
165191
}
166192

Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -605,11 +605,15 @@ extension SnippetBasedReferenceTests {
605605
)
606606
}
607607

608-
func makeTypesTranslator(componentsYAML: String) throws -> TypesFileTranslator {
608+
func makeTypesTranslator(
609+
featureFlags: FeatureFlags = [],
610+
ignoredDiagnosticMessages: Set<String> = [],
611+
componentsYAML: String
612+
) throws -> TypesFileTranslator {
609613
let components = try YAMLDecoder().decode(OpenAPI.Components.self, from: componentsYAML)
610614
return TypesFileTranslator(
611-
config: Config(mode: .types),
612-
diagnostics: XCTestDiagnosticCollector(test: self),
615+
config: Config(mode: .types, featureFlags: featureFlags),
616+
diagnostics: XCTestDiagnosticCollector(test: self, ignoredDiagnosticMessages: ignoredDiagnosticMessages),
613617
components: components
614618
)
615619
}
@@ -648,23 +652,35 @@ extension SnippetBasedReferenceTests {
648652
}
649653

650654
func assertResponsesTranslation(
655+
featureFlags: FeatureFlags = [],
656+
ignoredDiagnosticMessages: Set<String> = [],
651657
_ componentsYAML: String,
652658
_ expectedSwift: String,
653659
file: StaticString = #filePath,
654660
line: UInt = #line
655661
) throws {
656-
let translator = try makeTypesTranslator(componentsYAML: componentsYAML)
662+
let translator = try makeTypesTranslator(
663+
featureFlags: featureFlags,
664+
ignoredDiagnosticMessages: ignoredDiagnosticMessages,
665+
componentsYAML: componentsYAML
666+
)
657667
let translation = try translator.translateComponentResponses(translator.components.responses)
658668
try XCTAssertSwiftEquivalent(translation, expectedSwift, file: file, line: line)
659669
}
660670

661671
func assertRequestBodiesTranslation(
672+
featureFlags: FeatureFlags = [],
673+
ignoredDiagnosticMessages: Set<String> = [],
662674
_ componentsYAML: String,
663675
_ expectedSwift: String,
664676
file: StaticString = #filePath,
665677
line: UInt = #line
666678
) throws {
667-
let translator = try makeTypesTranslator(componentsYAML: componentsYAML)
679+
let translator = try makeTypesTranslator(
680+
featureFlags: featureFlags,
681+
ignoredDiagnosticMessages: ignoredDiagnosticMessages,
682+
componentsYAML: componentsYAML
683+
)
668684
let translation = try translator.translateComponentRequestBodies(translator.components.requestBodies)
669685
try XCTAssertSwiftEquivalent(translation, expectedSwift, file: file, line: line)
670686
}

Tests/OpenAPIGeneratorReferenceTests/XCTestDiagnosticCollector.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,12 @@ import XCTest
1717
// A diagnostic collector that fails the running test on a warning or error.
1818
struct XCTestDiagnosticCollector: DiagnosticCollector {
1919
var test: XCTestCase
20+
var ignoredDiagnosticMessages: Set<String> = []
2021

2122
func emit(_ diagnostic: Diagnostic) {
23+
guard !ignoredDiagnosticMessages.contains(diagnostic.message) else {
24+
return
25+
}
2226
print("Test emitted diagnostic: \(diagnostic.description)")
2327
switch diagnostic.severity {
2428
case .note:

0 commit comments

Comments
 (0)