From 0b52709ede6eb0cc11d17ca7f46889c1b8354329 Mon Sep 17 00:00:00 2001 From: fhasse95 <49185957+fhasse95@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:28:15 +0100 Subject: [PATCH] Add support for parameterized Swift Testing tests --- .../Kotlin/KotlinStatementTypes.swift | 2 + .../Kotlin/KotlinUnitTestTransformer.swift | 95 ++++++++++++++++++- .../Sources/SkipSyntax/StatementTypes.swift | 4 +- .../SkipSyntax/SwiftTestingArguments.swift | 83 ++++++++++++++++ .../ParameterizedTestingTests.swift | 67 +++++++++++++ 5 files changed, 246 insertions(+), 5 deletions(-) create mode 100644 skipstone/Sources/SkipSyntax/SwiftTestingArguments.swift create mode 100644 skipstone/Tests/SkipSyntaxTests/ParameterizedTestingTests.swift diff --git a/skipstone/Sources/SkipSyntax/Kotlin/KotlinStatementTypes.swift b/skipstone/Sources/SkipSyntax/Kotlin/KotlinStatementTypes.swift index 3f262f02..cf8e3a4c 100644 --- a/skipstone/Sources/SkipSyntax/Kotlin/KotlinStatementTypes.swift +++ b/skipstone/Sources/SkipSyntax/Kotlin/KotlinStatementTypes.swift @@ -1807,6 +1807,7 @@ final class KotlinFunctionDeclaration: KotlinStatement, KotlinMemberDeclaration var hasAsyncExplicitReturn = false var suppressSideEffects = false var isGenerated = false + var testArgumentsProviderName: String? var functionType: TypeSignature { return attributes.apply(toFunction: .function(parameters.map(\.signature), returnType, apiFlags, nil)) } @@ -1879,6 +1880,7 @@ final class KotlinFunctionDeclaration: KotlinStatement, KotlinMemberDeclaration static func translate(statement: FunctionDeclaration, translator: KotlinTranslator) -> KotlinFunctionDeclaration { let kstatement = KotlinFunctionDeclaration(statement: statement) + kstatement.testArgumentsProviderName = statement.testArgumentsProviderName kstatement.isOptionalInit = statement.isOptionalInit kstatement.modifiers = statement.modifiers kstatement.generics = statement.generics.resolvingSelf(in: statement) diff --git a/skipstone/Sources/SkipSyntax/Kotlin/KotlinUnitTestTransformer.swift b/skipstone/Sources/SkipSyntax/Kotlin/KotlinUnitTestTransformer.swift index f361a0c4..cfe65d37 100644 --- a/skipstone/Sources/SkipSyntax/Kotlin/KotlinUnitTestTransformer.swift +++ b/skipstone/Sources/SkipSyntax/Kotlin/KotlinUnitTestTransformer.swift @@ -77,7 +77,9 @@ final class KotlinUnitTestTransformer: KotlinTransformer { let isSwiftTesting = testFuncNames.contains(functionDeclaration.name) if isXCTest || isSwiftTesting { - if functionDeclaration.apiFlags.options.contains(.async) { + if functionDeclaration.testArgumentsProviderName != nil { + transformParameterizedTest(functionDeclaration, owningClass: owningClass, importPackages: &importPackages) + } else if functionDeclaration.apiFlags.options.contains(.async) { transformAsyncTest(functionDeclaration: functionDeclaration, owningClass: owningClass, importPackages: &importPackages) } else { functionDeclaration.annotations += ["@Test"] @@ -138,13 +140,15 @@ final class KotlinUnitTestTransformer: KotlinTransformer { if let index = codeBlock.statements.firstIndex(where: { $0 === functionDeclaration }) { functionDeclaration.role = .member functionDeclaration.extras = nil - if functionDeclaration.apiFlags.options.contains(.async) { + classDeclaration.members = [functionDeclaration] + functionDeclaration.parent = classDeclaration + if functionDeclaration.testArgumentsProviderName != nil { + transformParameterizedTest(functionDeclaration, owningClass: classDeclaration, globalProvider: true, importPackages: &importPackages) + } else if functionDeclaration.apiFlags.options.contains(.async) { transformAsyncTest(functionDeclaration: functionDeclaration, owningClass: classDeclaration, importPackages: &importPackages) } else { functionDeclaration.annotations += ["@Test"] } - classDeclaration.members = [functionDeclaration] - functionDeclaration.parent = classDeclaration codeBlock.statements[index] = classDeclaration classDeclaration.parent = codeBlock @@ -152,6 +156,89 @@ final class KotlinUnitTestTransformer: KotlinTransformer { } } + /// Keeps the typed Swift test as a helper and exposes one injectable case to JUnit. + /// The runner creates a new suite instance for each case, including async tests. + private func transformParameterizedTest( + _ function: KotlinFunctionDeclaration, + owningClass: KotlinClassDeclaration, + globalProvider: Bool = false, + importPackages: inout Set + ) { + guard let providerName = function.testArgumentsProviderName else { + return + } + + // Select the parameterized runner without replacing a custom runner + let runner = "@org.junit.runner.RunWith(skip.unit.SkipParameterizedTestRunner::class)" + owningClass.annotations.removeAll { $0 == KotlinClassDeclaration.testRunnerAnnotation } + + if owningClass.annotations.contains(where: { + $0.hasPrefix("@RunWith(") || $0.hasPrefix("@org.junit.runner.RunWith(") && $0 != runner + }) { + function.messages.append(Message( + kind: .error, + message: "Parameterized Swift tests cannot be combined with a custom @RunWith runner.", + sourceDerived: function + )) + return + } + + if !owningClass.annotations.contains(runner) { + owningClass.annotations.append(runner) + } + + // Create the argument provider for the generated JUnit test + let providerClass = providerName + "Provider" + let callProvider = globalProvider ? providerName : "\(owningClass.name).\(providerName)" + let provider = KotlinRawStatement(sourceCode: """ + class \(providerClass): skip.unit.SkipTestArgumentsProvider() { + override fun arguments(): List> = + \(callProvider)().map { it.kotlin(nocopy = true) } + .kotlin(nocopy = true) as List> + } + """) + + // Call the original test with its typed arguments + let callArguments = function.parameters.enumerated().map { index, parameter in + "arguments[\(index)] as \(parameter.declaredType.kotlin)" + }.joined(separator: ", ") + let invocation = "\(function.name)(\(callArguments))" + var lines = ["if (arguments == null) throw org.junit.AssumptionViolatedException(\"No test arguments\")"] + let isAsync = function.apiFlags.options.contains(.async) + + if isAsync { + importPackages.formUnion(["kotlinx.coroutines.*", "kotlinx.coroutines.test.*"]) + lines += [ + "val dispatcher = StandardTestDispatcher()", + "Dispatchers.setMain(dispatcher)", + "try {", + " runTest { withContext(Dispatchers.Main) { \(invocation) } }", + "} finally {", + " Dispatchers.resetMain()", + "}" + ] + } else { + lines.append(invocation) + } + + // Create the injectable wrapper and insert it before the original test + let wrapper = KotlinRawStatement(sourceCode: """ + \(isAsync ? "@OptIn(ExperimentalCoroutinesApi::class)\n" : "")@Test + fun \(providerName)_test( + @com.google.testing.junit.testparameterinjector.TestParameter(valuesProvider = \(providerClass)::class) + arguments: List? + ) { + \(lines.map { " " + $0 }.joined(separator: "\n")) + } + """) + + if let index = owningClass.members.firstIndex(where: { $0 === function }) { + owningClass.members.insert(contentsOf: [provider, wrapper], at: index) + provider.parent = owningClass + wrapper.parent = owningClass + } + } + private func transformAsyncTest(functionDeclaration: KotlinFunctionDeclaration, owningClass: KotlinClassDeclaration, importPackages: inout Set) { importPackages.insert("kotlinx.coroutines.*") importPackages.insert("kotlinx.coroutines.test.*") diff --git a/skipstone/Sources/SkipSyntax/StatementTypes.swift b/skipstone/Sources/SkipSyntax/StatementTypes.swift index d673114a..8e084401 100644 --- a/skipstone/Sources/SkipSyntax/StatementTypes.swift +++ b/skipstone/Sources/SkipSyntax/StatementTypes.swift @@ -1034,6 +1034,7 @@ final class ExtensionDeclaration: TypeDeclaration { final class FunctionDeclaration: Statement { let name: String let isOptionalInit: Bool + var testArgumentsProviderName: String? private(set) var returnType: TypeSignature private(set) var parameters: [Parameter] private(set) var asyncBehavior: AsyncBehavior @@ -1070,7 +1071,8 @@ final class FunctionDeclaration: Statement { override class func decode(syntax: SyntaxProtocol, extras: StatementExtras?, context: DecodeContext, in syntaxTree: SyntaxTree) -> [Statement]? { if syntax.kind == .functionDecl, let functionDecl = syntax.as(FunctionDeclSyntax.self) { if let declaration = decodeFunctionDeclaration(functionDecl, extras: extras, context: context, in: syntaxTree) { - return [declaration] + let provider = SwiftTestingArguments.provider(for: declaration, syntax: functionDecl, context: context, in: syntaxTree) + return [declaration] + (provider.map { [$0] } ?? []) } else { return [] } diff --git a/skipstone/Sources/SkipSyntax/SwiftTestingArguments.swift b/skipstone/Sources/SkipSyntax/SwiftTestingArguments.swift new file mode 100644 index 00000000..98010cf7 --- /dev/null +++ b/skipstone/Sources/SkipSyntax/SwiftTestingArguments.swift @@ -0,0 +1,83 @@ +import SwiftParser +import SwiftSyntax + +/// Lowers argument collections to a Swift provider so normal type inference and +/// expression translation also apply to expressions inside `@Test(arguments:)`. +enum SwiftTestingArguments { + static func provider( + for declaration: FunctionDeclaration, + syntax: FunctionDeclSyntax, + context: DecodeContext, + in syntaxTree: SyntaxTree + ) -> FunctionDeclaration? { + guard !syntaxTree.isBridgeFile, declaration.attributes.contains(.test), + let attribute = syntax.attributes.compactMap({ $0.as(AttributeSyntax.self) }).first(where: { + $0.attributeName.description.trimmingCharacters(in: .whitespacesAndNewlines) == "Test" + }), case .argumentList(let arguments) = attribute.arguments, + let first = arguments.firstIndex(where: { $0.label?.text == "arguments" }) else { + return nil + } + + let collections = Array(arguments[first...]) + let parameters = Array(syntax.signature.parameterClause.parameters) + guard !parameters.isEmpty, collections.count <= 2, + collections.count == 1 || parameters.count == 2, + syntax.genericParameterClause == nil, + !declaration.parameters.contains(where: { $0.isInOut || $0.isVariadic }) else { + declaration.messages.append(Message( + kind: .error, + message: "Skip supports @Test(arguments:) with one collection (including tuples), " + + "or two collections and two parameters; generic, inout and variadic test parameters are not supported.", + sourceDerived: declaration + )) + return nil + } + + let position = declaration.sourceRange?.start + let name = "__skipArguments_\(declaration.name)_\(position?.line ?? 0)_\(position?.column ?? 0)" + let types = parameters.map { $0.type.description.trimmingCharacters(in: .whitespacesAndNewlines) } + + var body: String + if collections.count == 1 { + let elementType = types.count == 1 ? types[0] : "(" + types.joined(separator: ", ") + ")" + let values = types.count == 1 ? "argument" : types.indices.map { "argument.\($0)" }.joined(separator: ", ") + body = """ + for argument in Array<\(elementType)>(\(collections[0].expression)) { + cases.append([\(values)]) + } + """ + } else { + body = """ + let firstArguments = Array<\(types[0])>(\(collections[0].expression)) + let secondArguments = Array<\(types[1])>(\(collections[1].expression)) + for first in firstArguments { + for second in secondArguments { + cases.append([first, second]) + } + } + """ + } + + let source = """ + \(context.memberOf == nil ? "" : "static ")func \(name)() -> [[Any?]] { + var cases: [[Any?]] = [] + \(body) + return cases + } + """ + + let parsed = Parser.parse(source: source) + guard let function = parsed.statements.first?.item.as(FunctionDeclSyntax.self), + let provider = FunctionDeclaration.decode( + syntax: function, + extras: nil, + context: context, + in: syntaxTree + )?.first as? FunctionDeclaration else { + return nil + } + + declaration.testArgumentsProviderName = name + return provider + } +} diff --git a/skipstone/Tests/SkipSyntaxTests/ParameterizedTestingTests.swift b/skipstone/Tests/SkipSyntaxTests/ParameterizedTestingTests.swift new file mode 100644 index 00000000..da0ca038 --- /dev/null +++ b/skipstone/Tests/SkipSyntaxTests/ParameterizedTestingTests.swift @@ -0,0 +1,67 @@ +import XCTest +@testable import SkipSyntax + +final class ParameterizedTestingTests: XCTestCase { + func testArgumentCollectionsUseParameterRunner() async throws { + try await check(swift: """ + import Testing + struct NumberTests { + static let values = [1, 2, 3] + @Test(arguments: Self.values) + func positive(value: Int) { + #expect(value > 0) + } + } + """, kotlin: "", fixup: { output in + XCTAssertTrue(output.contains("SkipParameterizedTestRunner::class")) + XCTAssertTrue(output.contains("SkipTestArgumentsProvider")) + XCTAssertTrue(output.contains("NumberTests.__skipArguments_positive")) + XCTAssertTrue(output.contains("arguments[0] as Int")) + XCTAssertTrue(output.contains("Array(Companion.values)"), output) + return "" + }) + } + + func testTupleAndCartesianArguments() async throws { + try await check(swift: """ + import Testing + struct TupleTests { + @Test(arguments: [(1, "a"), (2, "b")]) + func pair(number: Int, text: String) {} + @Test(arguments: 1...3, [true, false]) + func product(number: Int, flag: Bool) {} + } + """, kotlin: "", fixup: { output in + XCTAssertTrue(output.contains("arguments[1] as String")) + XCTAssertTrue(output.contains("arguments[1] as Boolean")) + XCTAssertTrue(output.contains("for (first in firstArguments"), output) + XCTAssertTrue(output.contains("for (second in secondArguments"), output) + return "" + }) + } + + func testFreestandingAsyncArguments() async throws { + try await check(swift: """ + import Testing + @Test(arguments: [1, 2]) + func asynchronous(value: Int) async throws { + #expect(value > 0) + } + """, kotlin: "", fixup: { output in + XCTAssertTrue(output.contains("class AsynchronousTests")) + XCTAssertTrue(output.contains("runTest { withContext(Dispatchers.Main)")) + XCTAssertTrue(output.contains("arguments[0] as Int")) + return "" + }) + } + + func testUnsupportedArgumentArityProducesDiagnostic() async throws { + try await checkProducesMessage(swift: """ + import Testing + struct Invalid { + @Test(arguments: [1], [2]) + func invalid(value: Int) {} + } + """) + } +}