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
use crate::core::config::ResolvedCrateConfig;
use crate::core::hash::{self, CommentStyle};
use crate::e2e::config::E2eConfig;
use crate::e2e::field_access::SwiftFirstClassMap;
use crate::e2e::fixture::Fixture;
use std::fmt::Write as FmtWrite;
use super::project::SWIFT_FORMAT_IGNORE_DIRECTIVE;
use super::{http, test_method};
#[allow(clippy::too_many_arguments)]
pub(super) fn render_test_file(
category: &str,
fixtures: &[&Fixture],
e2e_config: &E2eConfig,
module_name: &str,
class_name: &str,
function_name: &str,
result_var: &str,
args: &[crate::e2e::config::ArgMapping],
result_is_simple: bool,
client_factory: Option<&str>,
swift_first_class_map: &SwiftFirstClassMap,
config: &ResolvedCrateConfig,
type_defs: &[crate::core::ir::TypeDef],
has_http_fixtures: bool,
enums: &[crate::core::ir::EnumDef],
functions: &[crate::core::ir::FunctionDef],
errors: &[crate::core::ir::ErrorDef],
) -> String {
let file_input_scan = crate::e2e::codegen::file_inputs::FileInputScan::new(type_defs, enums);
// Detect whether any fixture in this group uses a file_path or bytes arg — if so
// the test class chdir's to <repo>/test_documents at setUp time so the
// fixture-relative paths in test bodies (e.g. "docx/fake.docx") resolve correctly.
// The Swift binding's `extractBytes`/`extractFile` e2e wrappers consult
// `FIXTURES_DIR` first, otherwise resolve against the current directory.
// Mirrors the Ruby/Python conftest pattern that chdirs to test_documents.
let needs_chdir = fixtures.iter().any(|f| {
let call_config =
e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
file_input_scan.fixture_uses_test_documents(f, call_config)
});
let mut out = String::new();
out.push_str(&hash::header(CommentStyle::DoubleSlash));
out.push_str(SWIFT_FORMAT_IGNORE_DIRECTIVE);
let _ = writeln!(out, "import XCTest");
let _ = writeln!(out, "import Foundation");
// URLSession et al. are in FoundationNetworking on Linux (swift-corelibs-foundation)
// but in plain Foundation on Apple platforms. The canImport guard makes the import
// a no-op where the submodule is absent.
let _ = writeln!(out, "#if canImport(FoundationNetworking)");
let _ = writeln!(out, "import FoundationNetworking");
let _ = writeln!(out, "#endif");
let _ = writeln!(out, "import {module_name}");
// RustBridge is needed for low-level types (RustVec<UInt8>, RustString) constructed
// in bytes/string argument setup. It is exposed as a product by the swift package
// for e2e test use.
let _ = writeln!(out, "import RustBridge");
let _ = writeln!(out);
let _ = writeln!(out, "/// E2e tests for category: {category}.");
let _ = writeln!(out, "final class {class_name}: XCTestCase {{");
if has_http_fixtures {
// Holds the spawned harness subprocess (if any) so tearDown can terminate it
// deterministically instead of leaving it orphaned when the suite exits.
//
// `nonisolated(unsafe)` because a mutable static is a hard error under the Swift 6
// language mode a `swift-tools-version: 6.0` package selects, and XCTest's `class
// setUp`/`class tearDown` are the only writers: the runner calls them once each per
// suite, before and after that suite's tests, so there is no concurrent access for the
// compiler's isolation checking to protect. Without the annotation every generated suite
// fails to compile, which is not a test failure the suite can report -- the whole target
// is simply unbuildable. ~keep
let _ = writeln!(
out,
" nonisolated(unsafe) private static var _harnessProcess: Process?"
);
let _ = writeln!(out);
}
// Always emit a setUp that spawns the harness and optionally chdirs.
let _ = writeln!(out, " override class func setUp() {{");
let _ = writeln!(out, " super.setUp()");
// Inject environment variables from e2e.env. `env` is a `BTreeMap`, so this already
// iterates in key order -- no separate sort needed to keep generation reproducible. ~keep
if !e2e_config.env.is_empty() {
for (key, value) in &e2e_config.env {
let _ = writeln!(
out,
" _ = \"{}\".withCString {{ val in",
value.replace('\\', "\\\\").replace('"', "\\\"")
);
let _ = writeln!(out, " \"{}\".withCString {{ key in", key);
let _ = writeln!(out, " setenv(key, val, 0)");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " }}");
}
}
// Spawn the harness subprocess if SUT_URL is not already set.
// Only emit when there are HTTP fixtures; consumers without HTTP tests
// don't need the harness.
if has_http_fixtures {
let _ = writeln!(
out,
" let _existing = ProcessInfo.processInfo.environment[\"SUT_URL\"]"
);
let _ = writeln!(out, " if _existing == nil {{");
let _ = writeln!(out, " let _harness = URL(fileURLWithPath: #filePath)");
let _ = writeln!(out, " .deletingLastPathComponent() // <Module>Tests/");
let _ = writeln!(out, " .deletingLastPathComponent() // Tests/");
let _ = writeln!(out, " .deletingLastPathComponent() // swift_e2e/");
let _ = writeln!(out, " .deletingLastPathComponent() // e2e/");
let _ = writeln!(out, " .appendingPathComponent(\"swift_e2e\")");
let _ = writeln!(out, " .appendingPathComponent(\".build/debug/Harness\")");
let _ = writeln!(out, " let proc = Process()");
let _ = writeln!(out, " proc.executableURL = _harness");
// Discard the harness's stdout/stderr via /dev/null rather than a Pipe: an
// undrained pipe blocks the child once its 64KB kernel buffer fills, and if the
// pipe's write end (inherited fd) survives an orphaned/zombie child, `swift-test`
// can block forever reading from it. /dev/null never fills and is never inherited
// in a way that keeps the parent's read blocked. ~keep
let _ = writeln!(out, " proc.standardOutput = FileHandle.nullDevice");
let _ = writeln!(out, " proc.standardError = FileHandle.nullDevice");
let _ = writeln!(out, " proc.standardInput = Pipe()");
let _ = writeln!(out, " Self._harnessProcess = proc");
let _ = writeln!(out, " do {{");
let _ = writeln!(out, " try proc.run()");
let _ = writeln!(out, " }} catch {{");
let _ = writeln!(
out,
" fatalError(\"Failed to start harness: \\(error)\")"
);
let _ = writeln!(out, " }}");
let _ = writeln!(out, " let deadline = Date(timeIntervalSinceNow: 15.0)");
let _ = writeln!(out, " var ready = false");
let host = &e2e_config.harness.host;
let port = e2e_config.harness.port;
let _ = writeln!(
out,
" let _probeURL = URL(string: \"http://{}:{}/\")!",
host, port
);
let _ = writeln!(out, " while Date.now < deadline {{");
let _ = writeln!(out, " if proc.isRunning == false {{ break }}");
let _ = writeln!(out, " var _probeReq = URLRequest(url: _probeURL)");
let _ = writeln!(out, " _probeReq.timeoutInterval = 0.5");
let _ = writeln!(out, " let _probeSema = DispatchSemaphore(value: 0)");
let _ = writeln!(
out,
" let _probeSession = URLSession(configuration: .ephemeral)"
);
// Readiness requires an actual HTTP response — a connection error (e.g.
// "connection refused" while the harness is still binding its listener)
// also completes the data task, so checking only "did the task complete"
// reports the harness ready before it can accept requests. Require both
// a nil error and an HTTPURLResponse (i.e. a real status code) before
// treating the probe as successful.
let _ = writeln!(out, " var _probeSucceeded = false");
let _ = writeln!(
out,
" _probeSession.dataTask(with: _probeReq) {{ _, response, error in"
);
let _ = writeln!(
out,
" if error == nil, response is HTTPURLResponse {{"
);
let _ = writeln!(out, " _probeSucceeded = true");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " _probeSema.signal()");
let _ = writeln!(out, " }}.resume()");
let _ = writeln!(
out,
" if _probeSema.wait(timeout: .now() + 0.6) == .timedOut {{"
);
let _ = writeln!(out, " usleep(100000)");
let _ = writeln!(out, " continue");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " if !_probeSucceeded {{");
let _ = writeln!(out, " usleep(100000)");
let _ = writeln!(out, " continue");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " ready = true");
let _ = writeln!(out, " break");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " if !ready {{");
let _ = writeln!(out, " proc.terminate()");
let _ = writeln!(
out,
" fatalError(\"Harness did not become ready within 15s\")"
);
let _ = writeln!(out, " }}");
// `ProcessInfo.processInfo.environment` is read-only; use the C `setenv`
// function to mutate the actual process environment so subsequent
// `getenv("SUT_URL")` lookups (and Swift's `ProcessInfo` snapshot) see it.
let _ = writeln!(
out,
" _ = \"http://{}:{}\".withCString {{ url in",
host, port
);
let _ = writeln!(out, " \"SUT_URL\".withCString {{ key in");
let _ = writeln!(out, " setenv(key, url, 1)");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " }}");
}
if needs_chdir {
// Chdir once at class setUp so all fixture file_path arguments resolve relative
// to the repository's test_documents directory.
//
// #filePath = <repo>/e2e/swift_e2e/Tests/<Module>E2ETests/<Class>.swift
// 5 deletingLastPathComponent() calls climb to the repo root before appending
// "test_documents". Mirrors the Ruby/Python conftest pattern that chdirs to
// test_documents.
let _ = writeln!(out, " let _testDocs = URL(fileURLWithPath: #filePath)");
let _ = writeln!(out, " .deletingLastPathComponent() // <Module>Tests/");
let _ = writeln!(out, " .deletingLastPathComponent() // Tests/");
let _ = writeln!(out, " .deletingLastPathComponent() // swift_e2e/");
let _ = writeln!(out, " .deletingLastPathComponent() // e2e/");
let _ = writeln!(out, " .deletingLastPathComponent() // <repo root>");
let _ = writeln!(
out,
" .appendingPathComponent(\"{}\")",
e2e_config.test_documents_dir
);
let _ = writeln!(
out,
" if FileManager.default.fileExists(atPath: _testDocs.path) {{"
);
let _ = writeln!(
out,
" FileManager.default.changeCurrentDirectoryPath(_testDocs.path)"
);
let _ = writeln!(out, " }}");
}
let _ = writeln!(out, " }}");
let _ = writeln!(out);
if has_http_fixtures {
// Reap the harness so it is never left listening as an orphan. `swift test` runs
// every class in one process, and setUp only spawns when SUT_URL is unset — so the
// class that spawned must also clear SUT_URL, or the next class would skip spawning
// and issue its requests against the server this tearDown just killed. Clearing it
// only when we own `_harnessProcess` preserves an externally supplied SUT_URL. ~keep
let _ = writeln!(out, " override class func tearDown() {{");
let _ = writeln!(out, " if let proc = _harnessProcess {{");
let _ = writeln!(out, " if proc.isRunning {{");
let _ = writeln!(out, " proc.terminate()");
let _ = writeln!(out, " proc.waitUntilExit()");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " _ = \"SUT_URL\".withCString {{ key in");
let _ = writeln!(out, " unsetenv(key)");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " }}");
let _ = writeln!(out, " _harnessProcess = nil");
let _ = writeln!(out, " super.tearDown()");
let _ = writeln!(out, " }}");
let _ = writeln!(out);
}
for fixture in fixtures {
if fixture.is_http_test() {
http::render_http_test_method(&mut out, fixture);
} else {
test_method::render_test_method(
&mut out,
fixture,
e2e_config,
function_name,
result_var,
args,
result_is_simple,
client_factory,
swift_first_class_map,
module_name,
config,
type_defs,
enums,
functions,
errors,
);
}
let _ = writeln!(out);
}
let _ = writeln!(out, "}}");
out
}