Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -138,20 +140,105 @@ 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
classDeclaration.assignParentReferences()
}
}

/// 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<String>
) {
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<List<Any?>> =
\(callProvider)().map { it.kotlin(nocopy = true) }
.kotlin(nocopy = true) as List<List<Any?>>
}
""")

// 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<Any?>?
) {
\(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<String>) {
importPackages.insert("kotlinx.coroutines.*")
importPackages.insert("kotlinx.coroutines.test.*")
Expand Down
4 changes: 3 additions & 1 deletion skipstone/Sources/SkipSyntax/StatementTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Expression>]
private(set) var asyncBehavior: AsyncBehavior
Expand Down Expand Up @@ -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 []
}
Expand Down
83 changes: 83 additions & 0 deletions skipstone/Sources/SkipSyntax/SwiftTestingArguments.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
67 changes: 67 additions & 0 deletions skipstone/Tests/SkipSyntaxTests/ParameterizedTestingTests.swift
Original file line number Diff line number Diff line change
@@ -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<Int>(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) {}
}
""")
}
}
Loading