Skip to content

Commit

Permalink
Tests: Augment Command Tests
Browse files Browse the repository at this point in the history
Augment Commands Tests to run against the Native and Swift Build build
systems.

- BuildCommandTests
- TestCommandTests
- RunCommandTests
- APIDiffTests
- PackageCommandTests

Also,
  - Add a new BuildCommandTest and RunCommandTest test case that ensures
    a package with target conditionals builds and runs successfully
  - update BuildSystemProvider.Kind to define a "useXcodeBuildSystemPath"
    variable instead of sprinkling the `buildSystem == .xcode` all over
    the place
  - Augment the Swift Build integration test to run `swift test`

TODO:
  - Instead of marking test failures as  "Skipped", See if we can mark
    them as "expected fail" so we are forced to update the test once the
    production code has been update to support the "feature".
  • Loading branch information
bkhouri committed Feb 5, 2025
1 parent 844a6b3 commit 063da6d
Show file tree
Hide file tree
Showing 21 changed files with 707 additions and 143 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// swift-tools-version: 6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "ExecutableTargetWhen",
products: [
.executable(
name: "test",
targets: ["ExecutableTargetWhen"]
)
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.executableTarget(
name: "ExecutableTargetWhen",
dependencies: [
.target(name:"LinuxOnly", condition: .when(platforms:[.linux])),
.target(name:"MacOSOnly", condition: .when(platforms:[.macOS])),
.target(name:"WindowsOnly", condition: .when(platforms:[.windows])),
.target(name:"AllPlatforms")
]
),
.target(
name: "AllPlatforms"
),
.target(
name: "LinuxOnly",
dependencies: [
"CLibArchive",
"AllPlatforms"
]
),
.target(
name: "MacOSOnly",
dependencies: [
"AllPlatforms"
]
),
.target(
name: "WindowsOnly",
dependencies: [
"AllPlatforms"
]
),
.systemLibrary(
name: "CLibArchive",
pkgConfig: "libarchive",
providers: [
.apt(["libarchive-dev"]),
]
),
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public func getPlatform() throws -> String {
#if os(Windows)
return "Windows"
#else
#if os(macOS)
return "macOS"
#else
#if os(linux)
return "Linux"
#else
return "Unknown platform"
#endif
#endif
#endif
}


public protocol MyProtocol {
static var name: String { get }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module CLibArchive [system] {
header "shim.h"
link "archive"
export *
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#include "archive.h"
#include "archive_entry.h"
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// The Swift Programming Language
// https://docs.swift.org/swift-book

import AllPlatforms

#if os(Windows)
import WindowsOnly
#else
#if os(macOS)
import MacOSOnly
#else
#if os(linux)
import LinuxOnly
#endif
#endif
#endif

let platform = try getPlatform()
print("Hello, world on \(platform)! OSplatform: \(OSPlatform.name)")
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import CLibArchive

import AllPlatforms

public struct OSPlatform: MyProtocol {

public static var name: String {
return "Linux"
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import AllPlatforms
public struct OSPlatform: MyProtocol {

public static var name: String {
return "macOS"
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import AllPlatforms

public struct OSPlatform: MyProtocol {

public static var name: String {
return "Windows"
}

}
3 changes: 2 additions & 1 deletion IntegrationTests/Tests/IntegrationTests/SwiftPMTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ final class SwiftPMTests: XCTestCase {
try withTemporaryDirectory { tmpDir in
let packagePath = tmpDir.appending(component: "foo")
try localFileSystem.createDirectory(packagePath)
try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "executable")
try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "library")
try sh(swiftBuild, "--package-path", packagePath, "--build-system", "swiftbuild")
try sh(swiftTest, "--package-path", packagePath, "--build-system", "swiftbuild")
}
}

Expand Down
6 changes: 3 additions & 3 deletions Sources/CoreCommands/SwiftCommandState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ public final class SwiftCommandState {
self.observabilityHandler.progress,
self.observabilityHandler.prompt
)
let isXcodeBuildSystemEnabled = self.options.build.buildSystem == .xcode
let isXcodeBuildSystemEnabled = self.options.build.buildSystem.useXcodeBuildSystemPath
let workspace = try Workspace(
fileSystem: self.fileSystem,
location: .init(
Expand All @@ -459,7 +459,7 @@ public final class SwiftCommandState {
configuration: .init(
skipDependenciesUpdates: options.resolver.skipDependencyUpdate,
prefetchBasedOnResolvedFile: options.resolver.shouldEnableResolverPrefetching,
shouldCreateMultipleTestProducts: toolWorkspaceConfiguration.wantsMultipleTestProducts || options.build.buildSystem == .xcode,
shouldCreateMultipleTestProducts: toolWorkspaceConfiguration.wantsMultipleTestProducts || self.options.build.buildSystem.useXcodeBuildSystemPath,
createREPLProduct: toolWorkspaceConfiguration.wantsREPLProduct,
additionalFileRules: isXcodeBuildSystemEnabled ? FileRuleDescription.xcbuildFileTypes : FileRuleDescription.swiftpmFileTypes,
sharedDependenciesCacheEnabled: self.options.caching.useDependenciesCache,
Expand Down Expand Up @@ -795,7 +795,7 @@ public final class SwiftCommandState {
workers: options.build.jobs ?? UInt32(ProcessInfo.processInfo.activeProcessorCount),
sanitizers: options.build.enabledSanitizers,
indexStoreMode: options.build.indexStoreMode.buildParameter,
isXcodeBuildSystemEnabled: options.build.buildSystem == .xcode,
isXcodeBuildSystemEnabled: self.options.build.buildSystem.useXcodeBuildSystemPath,
prepareForIndexing: prepareForIndexingMode,
debuggingParameters: .init(
debugInfoFormat: options.build.debugInfoFormat.buildParameter,
Expand Down
13 changes: 13 additions & 0 deletions Sources/SPMBuildCore/BuildSystem/BuildSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -182,3 +182,16 @@ public enum BuildSystemUtilities {
return try AbsolutePath(validating: env, relativeTo: workingDir)
}
}


extension BuildSystemProvider.Kind {

public var useXcodeBuildSystemPath: Bool {
switch self {
case .native: return false
case .swiftbuild: return true
case .xcode: return true
}
}

}
2 changes: 2 additions & 0 deletions Sources/SwiftBuildSupport/SwiftBuildSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,8 @@ public final class SwiftBuildSystem: SPMBuildCore.BuildSystem {

do {
try await withSession(service: service, name: buildParameters.pifManifest.pathString) { session, _ in
self.outputStream.send("Building for \(self.buildParameters.configuration == .debug ? "debugging" : "production")...\n")

// Load the workspace, and set the system information to the default
do {
try await session.loadWorkspace(containerPath: self.buildParameters.pifManifest.pathString)
Expand Down
22 changes: 14 additions & 8 deletions Sources/_InternalTestSupport/misc.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ public func testWithTemporaryDirectory<Result>(
}
}

public enum TestError: Error {
case platformNotSupported
}

@discardableResult public func fixture<T>(
name: String,
createGitRepo: Bool = true,
Expand Down Expand Up @@ -252,7 +256,7 @@ public func getBuildSystemArgs(for buildSystem: BuildSystemProvider.Kind?) -> [S

@discardableResult
public func executeSwiftBuild(
_ packagePath: AbsolutePath,
_ packagePath: AbsolutePath?,
configuration: Configuration = .Debug,
extraArgs: [String] = [],
Xcc: [String] = [],
Expand All @@ -269,14 +273,14 @@ public func executeSwiftBuild(
Xswiftc: Xswiftc,
buildSystem: buildSystem
)
let buildArgs = getBuildSystemArgs(for: buildSystem)
let buildArgs: [String] = getBuildSystemArgs(for: buildSystem)
return try await SwiftPM.Build.execute(args, packagePath: packagePath, env: env)
}

@discardableResult
public func executeSwiftRun(
_ packagePath: AbsolutePath,
_ executable: String,
_ packagePath: AbsolutePath?,
_ executable: String?,
configuration: Configuration = .Debug,
extraArgs: [String] = [],
Xcc: [String] = [],
Expand All @@ -293,13 +297,15 @@ public func executeSwiftRun(
Xswiftc: Xswiftc,
buildSystem: buildSystem
)
args.append(executable)
if let executable {
args.append(executable)
}
return try await SwiftPM.Run.execute(args, packagePath: packagePath, env: env)
}

@discardableResult
public func executeSwiftPackage(
_ packagePath: AbsolutePath,
_ packagePath: AbsolutePath?,
configuration: Configuration = .Debug,
extraArgs: [String] = [],
Xcc: [String] = [],
Expand All @@ -321,7 +327,7 @@ public func executeSwiftPackage(

@discardableResult
public func executeSwiftPackageRegistry(
_ packagePath: AbsolutePath,
_ packagePath: AbsolutePath?,
configuration: Configuration = .Debug,
extraArgs: [String] = [],
Xcc: [String] = [],
Expand All @@ -343,7 +349,7 @@ public func executeSwiftPackageRegistry(

@discardableResult
public func executeSwiftTest(
_ packagePath: AbsolutePath,
_ packagePath: AbsolutePath?,
configuration: Configuration = .Debug,
extraArgs: [String] = [],
Xcc: [String] = [],
Expand Down
2 changes: 1 addition & 1 deletion Sources/swift-bootstrap/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ struct SwiftBootstrapBuildTool: AsyncParsableCommand {
triple: self.hostToolchain.targetTriple,
flags: buildFlags,
architectures: architectures,
isXcodeBuildSystemEnabled: buildSystem == .xcode,
isXcodeBuildSystemEnabled: buildSystem.useXcodeBuildSystemPath,
driverParameters: .init(
explicitTargetDependencyImportCheckingMode: explicitTargetDependencyImportCheck == .error ? .error : .none,
useIntegratedSwiftDriver: useIntegratedSwiftDriver,
Expand Down
37 changes: 35 additions & 2 deletions Tests/CommandsTests/APIDiffTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import Basics
import Build
import Commands
import SPMBuildCore

@_spi(SwiftPMInternal)
import DriverSupport
Expand All @@ -24,7 +25,11 @@ import _InternalTestSupport
import Workspace
import XCTest

final class APIDiffTests: CommandsTestCase {
class APIDiffTestCase: CommandsBuildProviderTestCase {
override func setUpWithError() throws {
try XCTSkipIf(type(of: self) == APIDiffTestCase.self, "Pay no attention to the class behind the curtain.")
}

@discardableResult
private func execute(
_ args: [String],
Expand All @@ -34,7 +39,12 @@ final class APIDiffTests: CommandsTestCase {
var environment = env ?? [:]
// don't ignore local packages when caching
environment["SWIFTPM_TESTS_PACKAGECACHE"] = "1"
return try await SwiftPM.Package.execute(args, packagePath: packagePath, env: environment)
return try await executeSwiftPackage(
packagePath,
extraArgs: args,
env: environment,
buildSystem: buildSystemProvider
)
}

func skipIfApiDigesterUnsupportedOrUnset() throws {
Expand Down Expand Up @@ -449,3 +459,26 @@ final class APIDiffTests: CommandsTestCase {
}
}
}

class APIDiffNativeTests: APIDiffTestCase {

override open var buildSystemProvider: BuildSystemProvider.Kind {
return .native
}

override func skipIfApiDigesterUnsupportedOrUnset() throws {
try super.skipIfApiDigesterUnsupportedOrUnset()
}

}

class APIDiffSwiftBuildTests: APIDiffTestCase {

override open var buildSystemProvider: BuildSystemProvider.Kind {
return .swiftbuild
}

override func skipIfApiDigesterUnsupportedOrUnset() throws {
try super.skipIfApiDigesterUnsupportedOrUnset()
}
}
Loading

0 comments on commit 063da6d

Please sign in to comment.