{#- Once-per-suite mock-request-count helper (alef issue #443).
Context variables (see src/e2e/codegen/mock_assertions/helper.rs for the full contract):
- helper_name: function name
- total_path: mock server's total-count endpoint path
- one_path: mock server's single-key endpoint path
Emits ONE private throwing INSTANCE method (deliberately not `static` -- see below) using this
backend's own URLSession + DispatchSemaphore synchronous-network idiom (see swift/http.rs's
`render_call` and swift/test_file.rs's harness-readiness probe, both already generated into
every test file) -- Foundation is already unconditionally imported by every generated test
file, so this helper adds no new import. `throws` lets a single failed mock-server request fail
only the ONE test asserting on it (XCTest catches a thrown error per test method), rather than
aborting the whole suite the way `fatalError` (used only for suite-level harness setup
elsewhere in this backend) would. Callers build `pathAndQuery` from
"{{ total_path }}?prefix=<p>" (mock.requests.total) or "{{ one_path }}?key=<k>"
(mock.requests["<k>"]) -- see mock_assertions::model::MockQuery -- and invoke this with `try`
since it throws.
~keep NOT `static`, unlike java/kotlin's identical-looking helper: every call site here is a
bare (unqualified) call emitted INSIDE another instance method of the same
`final class ...: XCTestCase` (see swift/test_method.rs's `render_test_method`), and Swift --
unlike Java/Kotlin -- refuses an unqualified reference to a `static` member from instance
context ("static member '...' cannot be used on instance of type '...'"). Verified by
compiling this exact rendered shape with `swiftc`: `private static func` failed with exactly
that error from a real instance test method; `private func` (below) compiles and runs.
#}
private func {{ helper_name }}(_ baseUrl: String, _ pathAndQuery: String) throws -> Int {
let url = URL(string: baseUrl + pathAndQuery)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
var _capturedData: Data?
var _capturedError: Error?
let _sema = DispatchSemaphore(value: 0)
URLSession(configuration: .ephemeral).dataTask(with: request) { data, _, error in
_capturedData = data
_capturedError = error
_sema.signal()
}.resume()
_sema.wait()
if let error = _capturedError {
throw error
}
let _body = String(data: _capturedData ?? Data(), encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard let _count = Int(_body) else {
throw NSError(
domain: "AlefMockRequestCount",
code: 1,
userInfo: [NSLocalizedDescriptionKey: "{{ helper_name }}: unexpected response body: \(_body)"]
)
}
return _count
}