From cf8237ff67ec2bad3aaf5af96ca5caedb54cf2fb Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 27 Sep 2026 19:35:29 +0800 Subject: [PATCH 1/3] Bump toolchains to Swift 6.3 and Xcode 26.6 Remove obsolete compiler compatibility paths and update CI runners. Fix modern Foundation tests and validate the official WebAssembly SDK. --- .github/workflows/compatibility_tests.yml | 6 +- .github/workflows/macos.yml | 9 +-- .github/workflows/swiftlint.yml | 26 +++--- .github/workflows/ubuntu.yml | 12 +-- .github/workflows/wasm.yml | 26 +++--- .github/workflows/windows.yml | 10 +-- .gitignore | 1 - .spi.yml | 2 +- .swiftlint.yml | 4 +- CONTRIBUTING.md | 8 +- Package.swift | 3 +- README.md | 7 +- Sources/OpenCombine/CombineIdentifier.swift | 2 +- Sources/OpenCombine/Helpers/Locking.swift | 2 +- .../Publishers/Publishers.Breakpoint.swift | 2 +- .../Publishers.MapKeyPath.swift.gyb | 2 +- .../Publishers/Publishers.Merge.swift | 2 +- .../Publishers/Publishers.Zip.swift | 2 +- .../Subscribers/Subscribers.Completion.swift | 4 - .../Subscribers/Subscribers.Demand.swift | 4 - .../DispatchQueue+Scheduler.swift | 6 +- .../Helpers/Locking.swift | 2 +- .../Helpers/Portability.swift | 47 ++--------- .../OperationQueue+Scheduler.swift | 16 ++-- .../PropertyListEncoder.swift | 4 - .../OpenCombineFoundation/URLSession.swift | 5 +- Tests/.swiftlint.yml | 3 - .../FutureConcurrencyTests.swift | 3 +- .../PublisherConcurrencyTests.swift | 35 +------- .../DispatchQueueSchedulerTests.swift | 11 +-- .../FoundationTests/JSONDecoderTests.swift | 2 +- .../FoundationTests/JSONEncoderTests.swift | 2 +- .../KeyValueObservingPublisherTests.swift | 2 +- .../NotificationCenterTests.swift | 74 ++++++++++++++++- .../OperationQueueSchedulerTests.swift | 8 +- .../PropertyListDecoderTests.swift | 2 +- .../PropertyListEncoderTests.swift | 2 +- .../RunLoopSchedulerTests.swift | 8 +- .../FoundationTests/TimerPublisherTests.swift | 2 +- .../FoundationTests/URLSessionTests.swift | 30 +++---- .../Helpers/AssertCrashes.swift | 2 +- .../Helpers/CommonTests.swift | 6 -- .../ObservableObjectTests.swift | 17 +++- .../PublisherTests/CatchTests.swift | 2 +- .../PublisherTests/CombineLatestTests.swift | 4 +- .../PublisherTests/FutureTests.swift | 11 +-- .../PublisherTests/MapKeyPathTests.swift | 2 +- .../PublisherTests/SequenceTests.swift | 36 ++++----- .../PublisherTests/ZipTests.swift | 4 +- utils/discover_tests.py | 79 ------------------- utils/gyb.py | 2 +- utils/lint.sh | 41 ++++++++++ 52 files changed, 277 insertions(+), 327 deletions(-) delete mode 100644 utils/discover_tests.py create mode 100644 utils/lint.sh diff --git a/.github/workflows/compatibility_tests.yml b/.github/workflows/compatibility_tests.yml index 475268e01..a5dfe113d 100644 --- a/.github/workflows/compatibility_tests.yml +++ b/.github/workflows/compatibility_tests.yml @@ -13,11 +13,11 @@ jobs: fail-fast: false matrix: include: - - os: macos-13 - xcode-version: "15.2" # Swift 5.9.2 + - os: macos-26 + xcode-version: "26.6" # Swift 6.3.3 runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Setup Xcode uses: OpenSwiftUIProject/setup-xcode@v2 with: diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 553653ffb..6cd9d2aff 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -13,11 +13,11 @@ jobs: fail-fast: false matrix: include: - - os: macos-13 - xcode-version: "15.2" # Swift 5.9.2 + - os: macos-26 + xcode-version: "26.6" # Swift 6.3.3 runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Setup Xcode uses: OpenSwiftUIProject/setup-xcode@v2 with: @@ -43,13 +43,12 @@ jobs: -Xswiftc -warnings-as-errors \ --build-path .build-test-debug-sanitize-thread - name: Build and run tests in release mode - if: ${{ matrix.xcode-version != '14.3.1' }} # error: no input files specified. See llvm-profdata merge -help run: | swift test \ -c release \ -Xswiftc -warnings-as-errors \ --enable-code-coverage \ --build-path .build-test-release - - uses: codecov/codecov-action@v3 + - uses: codecov/codecov-action@v7 with: verbose: true diff --git a/.github/workflows/swiftlint.yml b/.github/workflows/swiftlint.yml index fc4b82960..f4143358c 100644 --- a/.github/workflows/swiftlint.yml +++ b/.github/workflows/swiftlint.yml @@ -5,22 +5,22 @@ on: paths: - ".github/workflows/swiftlint.yml" - ".swiftlint.yml" + - "Tests/.swiftlint.yml" + - "utils/lint.sh" - "**/*.swift" jobs: SwiftLint: - runs-on: ubuntu-22.04 + runs-on: macos-26 steps: - - uses: actions/checkout@v4 - # Fetch current versions of files - - name: Fetch base ref - run: | - git fetch --prune --no-tags --depth=1 origin +refs/heads/${{ github.base_ref }}:refs/heads/${{ github.base_ref }} - # Diff pull request to current files, then SwiftLint changed files - - name: GitHub Action for SwiftLint - uses: mayk-it/action-swiftlint@3.2.2 - env: - DIFF_BASE: ${{ github.base_ref }} - DIFF_HEAD: HEAD + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Setup Xcode + uses: OpenSwiftUIProject/setup-xcode@v2 with: - args: --strict + xcode-version: "26.6" + - name: Check new SwiftLint violations + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: bash utils/lint.sh "$BASE_SHA" diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 19e7ceddc..07035b578 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -12,17 +12,17 @@ jobs: strategy: fail-fast: false matrix: - swift_version: ["5.9.2"] - os: [ubuntu-20.04, ubuntu-22.04] + swift_version: ["6.3.3"] + os: [ubuntu-22.04, ubuntu-24.04] include: - - os: ubuntu-20.04 - os_name: focal - os: ubuntu-22.04 os_name: jammy + - os: ubuntu-24.04 + os_name: noble runs-on: ${{ matrix.os }} container: swift:${{ matrix.swift_version }}-${{ matrix.os_name }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: Building and running tests in debug mode with coverage run: | swift test \ @@ -46,6 +46,6 @@ jobs: -c release \ -Xswiftc -warnings-as-errors \ --build-path .build-test-release - - uses: codecov/codecov-action@v3 + - uses: codecov/codecov-action@v7 with: verbose: true diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml index 3106e716c..7e538bad3 100644 --- a/.github/workflows/wasm.yml +++ b/.github/workflows/wasm.yml @@ -7,22 +7,16 @@ on: branches: [main] jobs: - wasmer_test: + wasm_test: name: Execute tests on WASM - strategy: - fail-fast: false - matrix: - swift_version: ["wasm-5.9.1-RELEASE", "wasm-5.10-SNAPSHOT-2024-01-13-a"] - os: [ubuntu-22.04] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-24.04 + container: swift:6.3.3-noble steps: - - uses: actions/checkout@v4 - - uses: swiftwasm/setup-swiftwasm@v1 - with: - swift-version: ${{ matrix.swift_version }} - - name: build + - uses: actions/checkout@v6 + - name: Install Swift SDK for WebAssembly run: | - swift build - - name: test - run: | - swift test \ No newline at end of file + swift sdk install \ + https://download.swift.org/swift-6.3.3-release/wasm-sdk/swift-6.3.3-RELEASE/swift-6.3.3-RELEASE_wasm.artifactbundle.tar.gz \ + --checksum cabfa08b73bb8ac783927ecd15fa386e99d0c139c5f232445067bcf58379cae7 + - name: Build and run tests on WebAssembly + run: swift test --swift-sdk swift-6.3.3-RELEASE_wasm diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 8531f200a..ce95cb5ce 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -13,14 +13,14 @@ jobs: fail-fast: false matrix: include: - - os: windows-2019 - swift_version: "5.9.2" + - os: windows-2025 + swift_version: "6.3.3" runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - uses: compnerd/gha-setup-swift@main with: - branch: swift-${{ matrix.swift_version }}-release - tag: ${{ matrix.swift_version }}-RELEASE + swift-version: swift-${{ matrix.swift_version }}-release + swift-build: ${{ matrix.swift_version }}-RELEASE - name: Building and running tests in debug mode run: swift test diff --git a/.gitignore b/.gitignore index 37c2f6185..0e64221cb 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,6 @@ /Packages /*.xcodeproj /.swiftpm -Tests/LinuxMain.swift # Created by https://www.gitignore.io/api/Xcode # Edit at https://www.gitignore.io/?templates=Xcode diff --git a/.spi.yml b/.spi.yml index c580fca26..a30aa5863 100644 --- a/.spi.yml +++ b/.spi.yml @@ -1,5 +1,5 @@ version: 1 builder: configs: - - swift_version: 5.9 + - swift_version: 6.3 documentation_targets: [OpenCombine, OpenCombineDispatch, OpenCombineFoundation] diff --git a/.swiftlint.yml b/.swiftlint.yml index d5cf4f737..f467db306 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -64,11 +64,13 @@ opt_in_rules: - toggle_bool - unneeded_parentheses_in_closure_argument - untyped_error_in_catch - - unused_import - vertical_parameter_alignment_on_call - vertical_whitespace_closing_braces - yoda_condition +analyzer_rules: + - unused_import + implicit_return: included: - closure diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 42263062c..16d1df285 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,12 +1,13 @@ # Contributing -In order to work on this project you will need Xcode 10.2 and Swift 5.0 or later. +Use Swift 6.3 or later. On Apple platforms, use Xcode 26.6 or later. +The package uses Swift 5 language mode. Please refer to the [issue #1](https://github.com/OpenCombine/OpenCombine/issues/1) for the list of operators that remain unimplemented, as well as the [RemainingCombineInterface.swift](https://github.com/OpenCombine/OpenCombine/blob/master/RemainingCombineInterface.swift) file. The latter contains the generated interface of Apple's Combine from the latest Xcode version. When the functionality is implemented in OpenCombine, it should be removed from the RemainingCombineInterface.swift file. You can refer to [this repo](https://github.com/OpenCombine/combine-interfaces) to observe Apple's Combine API and documentation changes between different Xcode (beta) versions. -You can run compatibility tests against Apple's Combine. In order to do that you will need either macOS 10.14 with iOS 13 simulator installed (since the only way we can get Apple's Combine on macOS 10.14 is using the simulator), or macOS 10.15 (Apple's Combine is bundled with the OS). Execute the following command from the root of the package: +You can run compatibility tests against Apple's Combine on macOS with Xcode 26.6 or later. Execute the following command from the root of the package: ``` $ make test-compatibility @@ -16,6 +17,9 @@ Or enable the `-DOPENCOMBINE_COMPATIBILITY_TEST` compiler flag in Xcode's build > NOTE: Before starting to work on some feature, please consult the [GitHub project](https://github.com/OpenCombine/OpenCombine/projects/2) to make sure that nobody's already making progress on the same feature! If not, then please create a draft PR to indicate that you're beginning your work. +Run `bash utils/lint.sh origin/main` to check SwiftLint violations introduced by your changes. +The script uses the base revision as a temporary baseline for existing violations. + #### Releasing a new version 1. Create a new branch from master and call it `release/..`. diff --git a/Package.swift b/Package.swift index b7343aab6..1afd032ac 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.9 +// swift-tools-version:6.3 import Foundation import PackageDescription @@ -91,6 +91,7 @@ let package = Package( openCombineDispatchTarget, openCombineTestsTarget, ], + swiftLanguageModes: [.v5], cxxLanguageStandard: .cxx17 ) diff --git a/README.md b/README.md index b94c2dc0a..796f4b965 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,9 @@ The documentation of the package can be found at [OpenCombine Documentation](htt ### Installation + +The current branch requires Swift 6.3 or later. On Apple platforms, use Xcode 26.6 or later. +The package uses Swift 5 language mode. `OpenCombine` contains three public targets: `OpenCombine`, `OpenCombineFoundation` and `OpenCombineDispatch` (the fourth one, `COpenCombineHelpers`, is considered private. Don't import it in your projects). OpenCombine itself does not have any dependencies. Not even Foundation or Dispatch. If you want to use OpenCombine with Dispatch (for example for using `DispatchQueue` as `Scheduler` for operators like `debounce`, `receive(on:)` etc.), you will need to import both `OpenCombine` and `OpenCombineDispatch`. The same applies to Foundation: if you want to use, for instance, `NotificationCenter` or `URLSession` publishers, you'll need to also import `OpenCombineFoundation`. @@ -51,9 +54,9 @@ targets: [ ``` ###### Xcode -`OpenCombine` can also be added as a SwiftPM dependency directly in your Xcode project *(requires Xcode 11 upwards)*. +`OpenCombine` can also be added as a SwiftPM dependency directly in your Xcode project *(requires Xcode 26.6 or later)*. -To do so, open Xcode, use **File** → **Swift Packages** → **Add Package Dependency…**, enter the [repository URL](https://github.com/OpenSwiftUIProject/OpenCombine.git), choose the latest available version, and activate the checkboxes: +To do so, open Xcode, use **File** → **Add Package Dependencies…**, enter the [repository URL](https://github.com/OpenSwiftUIProject/OpenCombine.git), choose the latest available version, and activate the checkboxes:

Select the OpenCombine and OpenCombineDispatch targets=5.5) import _Concurrency -#endif extension Subscribers { @@ -28,9 +26,7 @@ extension Subscribers.Completion: Equatable where Failure: Equatable {} extension Subscribers.Completion: Hashable where Failure: Hashable {} -#if canImport(_Concurrency) && compiler(>=5.5) || compiler(>=5.5.1) extension Subscribers.Completion: Sendable {} -#endif extension Subscribers.Completion { private enum CodingKeys: String, CodingKey { diff --git a/Sources/OpenCombine/Subscribers/Subscribers.Demand.swift b/Sources/OpenCombine/Subscribers/Subscribers.Demand.swift index f7c280499..d71566658 100644 --- a/Sources/OpenCombine/Subscribers/Subscribers.Demand.swift +++ b/Sources/OpenCombine/Subscribers/Subscribers.Demand.swift @@ -7,9 +7,7 @@ // swiftlint:disable attributes -#if canImport(_Concurrency) && compiler(>=5.5) import _Concurrency -#endif extension Subscribers { @@ -488,6 +486,4 @@ extension Subscribers { } } -#if canImport(_Concurrency) && compiler(>=5.5) || compiler(>=5.5.1) extension Subscribers.Demand: Sendable {} -#endif diff --git a/Sources/OpenCombineDispatch/DispatchQueue+Scheduler.swift b/Sources/OpenCombineDispatch/DispatchQueue+Scheduler.swift index 125397b6f..7545e4eee 100644 --- a/Sources/OpenCombineDispatch/DispatchQueue+Scheduler.swift +++ b/Sources/OpenCombineDispatch/DispatchQueue+Scheduler.swift @@ -299,7 +299,7 @@ extension DispatchQueue { queue.async(group: options.group, qos: options.qos, flags: options.flags, - execute: action) + execute: { action() }) } public func schedule(after date: SchedulerTimeType, @@ -310,7 +310,7 @@ extension DispatchQueue { queue.asyncAfter(deadline: date.dispatchTime, qos: options.qos, flags: options.flags, - execute: action) + execute: { action() }) } /// Performs the action at some time after the specified date, at the specified @@ -413,7 +413,7 @@ private func clampedIntProduct(_ lhs: Int64, _ rhs: Int64) -> Int64 { extension DispatchTime { fileprivate func polyfillDistance(to other: DispatchTime) -> DispatchTimeInterval { -#if canImport(Darwin) && compiler(>=5.1) +#if canImport(Darwin) if #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) { return distance(to: other) } diff --git a/Sources/OpenCombineFoundation/Helpers/Locking.swift b/Sources/OpenCombineFoundation/Helpers/Locking.swift index d09bd1be5..37b89149b 100644 --- a/Sources/OpenCombineFoundation/Helpers/Locking.swift +++ b/Sources/OpenCombineFoundation/Helpers/Locking.swift @@ -6,7 +6,7 @@ // #if canImport(COpenCombineHelpers) -@_implementationOnly import COpenCombineHelpers +internal import COpenCombineHelpers #endif import OpenCombine diff --git a/Sources/OpenCombineFoundation/Helpers/Portability.swift b/Sources/OpenCombineFoundation/Helpers/Portability.swift index fc8eaca3d..7614d5481 100644 --- a/Sources/OpenCombineFoundation/Helpers/Portability.swift +++ b/Sources/OpenCombineFoundation/Helpers/Portability.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 28.10.2020. // -#if canImport(CoreFoundation) +#if canImport(Darwin) import CoreFoundation #endif @@ -19,8 +19,6 @@ import Foundation /// /// We could use CoreFoundation everywhere, but the `RunLoop.getCFRunloop()` method /// is marked deprecated on the swift-corelibs-foundation main branch. -/// -/// Also, there are sume bugs in swift-corelibs-foundation in earlier Swift version. internal struct Timer { #if canImport(Darwin) @@ -96,36 +94,16 @@ internal struct Timer { #endif } -#if canImport(CoreFoundation) - fileprivate func getCFRunLoopTimer() -> CFRunLoopTimer? { #if canImport(Darwin) + fileprivate func getCFRunLoopTimer() -> CFRunLoopTimer? { return underlyingTimer -#elseif swift(<5.2) - // Here we use the fact that in the specified version of swift-corelibs-foundation - // the memory layout of Foundation.Timer is as follows: - // https://github.com/apple/swift-corelibs-foundation/blob/4cd3bf083b4705d25ac76ef8d038a06bc586265a/Foundation/Timer.swift#L18-L29 - - // The first 2 words are reserved for reference counting - let firstFieldOffset = MemoryLayout.size * 2 - - return Unmanaged - .passUnretained(underlyingTimer) - .toOpaque() - .load(fromByteOffset: firstFieldOffset, - as: CFRunLoopTimer?.self) -#else - fatalError("unreachable") -#endif } -#endif // canImport(CoreFoundation) +#endif // canImport(Darwin) } extension RunLoop { internal func add(_ timer: Timer, forMode mode: RunLoop.Mode) { - // There is a bug in swift-corelibs-foundation prior to Swift 5.2 where - // the timer is added to the current run loop instead of the one we're calling - // this method on, so we fall back to CoreFoundation. -#if canImport(Darwin) || swift(<5.2) +#if canImport(Darwin) CFRunLoopAddTimer(getCFRunLoop(), timer.getCFRunLoopTimer(), mode.asCFRunLoopMode()) @@ -138,26 +116,15 @@ extension RunLoop { #if canImport(Darwin) CFRunLoopPerformBlock(getCFRunLoop(), CFRunLoopMode.defaultMode.rawValue, block) #else - perform(block) + perform { block() } #endif } } -#if canImport(CoreFoundation) +#if canImport(Darwin) extension RunLoop.Mode { fileprivate func asCFRunLoopMode() -> CFRunLoopMode { -#if canImport(Darwin) return CFRunLoopMode(rawValue as CFString) -#else - return rawValue.withCString { - let encoding = CFStringBuiltInEncodings.UTF8.rawValue - return CFStringCreateWithCString( - nil, - $0, - encoding - ) - } -#endif } } -#endif // canImport(CoreFoundation) +#endif // canImport(Darwin) diff --git a/Sources/OpenCombineFoundation/OperationQueue+Scheduler.swift b/Sources/OpenCombineFoundation/OperationQueue+Scheduler.swift index b9a07697a..ec71c4f4c 100644 --- a/Sources/OpenCombineFoundation/OperationQueue+Scheduler.swift +++ b/Sources/OpenCombineFoundation/OperationQueue+Scheduler.swift @@ -157,7 +157,9 @@ extension OperationQueue { public struct SchedulerOptions { } - private final class DelayReadyOperation: Operation, Cancellable { + private final class DelayReadyOperation + : Operation, Cancellable, @unchecked Sendable + { fileprivate final class CancellationContext: Cancellable { let lock = UnfairLock.allocate() @@ -268,10 +270,9 @@ extension OperationQueue { } private func becomeReady() { -// Smart key paths don't work with NSOperation in swift-corelibs-foundation prior to -// Swift 5.1 and on OS version prior to iOS 11. +// Smart key paths don't work with NSOperation on OS versions prior to iOS 11. // The string key paths work fine everywhere on Darwin platforms. -#if canImport(Darwin) || swift(<5.1) +#if canImport(Darwin) willChangeValue(forKey: "isReady") #else willChangeValue(for: \.isReady) @@ -281,10 +282,9 @@ extension OperationQueue { readyFromAfter = true readyFromAfterLock.unlock() -// Smart key paths don't work with NSOperation in swift-corelibs-foundation prior to -// Swift 5.1 and on OS version prior to iOS 11. +// Smart key paths don't work with NSOperation on OS versions prior to iOS 11. // The string key paths work fine everywhere on Darwin platforms. -#if canImport(Darwin) || swift(<5.1) +#if canImport(Darwin) didChangeValue(forKey: "isReady") #else didChangeValue(for: \.isReady) @@ -301,7 +301,7 @@ extension OperationQueue { public func schedule(options: SchedulerOptions?, _ action: @escaping () -> Void) { - let op = BlockOperation(block: action) + let op = BlockOperation { action() } queue.addOperation(op) } diff --git a/Sources/OpenCombineFoundation/PropertyListEncoder.swift b/Sources/OpenCombineFoundation/PropertyListEncoder.swift index 05eefb2d8..4694c1089 100644 --- a/Sources/OpenCombineFoundation/PropertyListEncoder.swift +++ b/Sources/OpenCombineFoundation/PropertyListEncoder.swift @@ -8,9 +8,6 @@ import Foundation import OpenCombine -// PropertyListEncoder and PropertyListDecoder are unavailable in -// swift-corelibs-foundation prior to Swift 5.1. -#if canImport(Darwin) || swift(>=5.1) extension PropertyListEncoder: TopLevelEncoder { public typealias Output = Data } @@ -18,4 +15,3 @@ extension PropertyListEncoder: TopLevelEncoder { extension PropertyListDecoder: TopLevelDecoder { public typealias Input = Data } -#endif diff --git a/Sources/OpenCombineFoundation/URLSession.swift b/Sources/OpenCombineFoundation/URLSession.swift index 8bcab45a5..82e1641a2 100644 --- a/Sources/OpenCombineFoundation/URLSession.swift +++ b/Sources/OpenCombineFoundation/URLSession.swift @@ -167,8 +167,9 @@ extension URLSession.OCombine.DataTaskPublisher { return } if self.task == nil { - task = parent.session.dataTask(with: parent.request, - completionHandler: handleResponse) + task = parent.session.dataTask(with: parent.request) { + self.handleResponse(data: $0, response: $1, error: $2) + } } self.demand += demand let task = self.task diff --git a/Tests/.swiftlint.yml b/Tests/.swiftlint.yml index 035b903a9..127dbc9e0 100644 --- a/Tests/.swiftlint.yml +++ b/Tests/.swiftlint.yml @@ -1,6 +1,3 @@ -excluded: - - LinuxMain.swift - disabled_rules: - explicit_acl - explicit_top_level_acl diff --git a/Tests/OpenCombineTests/ConcurrencyTests/FutureConcurrencyTests.swift b/Tests/OpenCombineTests/ConcurrencyTests/FutureConcurrencyTests.swift index 7bc639eac..c47d6ccfd 100644 --- a/Tests/OpenCombineTests/ConcurrencyTests/FutureConcurrencyTests.swift +++ b/Tests/OpenCombineTests/ConcurrencyTests/FutureConcurrencyTests.swift @@ -13,8 +13,7 @@ import Combine import OpenCombine #endif -// swiftlint:disable:next line_length -#if !os(Windows) && !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(Windows) && !os(WASI) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) final class FutureConcurrencyTests: XCTestCase { diff --git a/Tests/OpenCombineTests/ConcurrencyTests/PublisherConcurrencyTests.swift b/Tests/OpenCombineTests/ConcurrencyTests/PublisherConcurrencyTests.swift index 24f6a8e4c..d8449b31a 100644 --- a/Tests/OpenCombineTests/ConcurrencyTests/PublisherConcurrencyTests.swift +++ b/Tests/OpenCombineTests/ConcurrencyTests/PublisherConcurrencyTests.swift @@ -13,8 +13,7 @@ import Combine import OpenCombine #endif -// swiftlint:disable:next line_length -#if !os(Windows) && !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(Windows) && !os(WASI) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) final class PublisherConcurrencyTests: XCTestCase { @@ -939,9 +938,6 @@ final class PublisherConcurrencyTests: XCTestCase { let numberOfTasksFinished = Atomic(0) - var deinitCount = 0 - let onDeinit = { deinitCount += 1 } - try await withThrowingTaskGroup(of: Void.self) { group in group.addTask { defer { numberOfTasksFinished += 1 } @@ -961,7 +957,7 @@ final class PublisherConcurrencyTests: XCTestCase { group.addTask { // Send completion _after_ we request some values. try await Task.sleep(nanoseconds: 20_000_000) - publisher.send(completion: .failure(RefError(onDeinit: onDeinit))) + publisher.send(completion: .failure(RefError())) numberOfTasksFinished += 1 } try await group.waitForAll() @@ -972,11 +968,6 @@ final class PublisherConcurrencyTests: XCTestCase { #if !canImport(Darwin) XCTAssertEqual(subscription.history, [.requested(.max(1)), .requested(.max(1))]) #endif - - // FIXME: onDeinit will be called after this function and `defer { XCTAssertEqual(deinitCount, 1) }` is also not working - #if swift(<5.8) - XCTAssertEqual(deinitCount, 1) - #endif withExtendedLifetime(publisher.erasedSubscriber) {} } @@ -990,10 +981,7 @@ final class PublisherConcurrencyTests: XCTestCase { let asyncPublisher = publisher.values let asyncIterator = IteratorWrapper(asyncPublisher.makeAsyncIterator()) - var deinitCount = 0 - let onDeinit = { deinitCount += 1 } - - publisher.send(completion: .failure(RefError(onDeinit: onDeinit))) + publisher.send(completion: .failure(RefError())) do { let value = try await asyncIterator.next() @@ -1002,10 +990,6 @@ final class PublisherConcurrencyTests: XCTestCase { } XCTAssertEqual(subscription.history, []) - #if swift(<5.8) - // FIXME: onDeinit will be called after this function and `defer { XCTAssertEqual(deinitCount, 1) }` is also not working - XCTAssertEqual(deinitCount, 1) - #endif let value = try await asyncIterator.next() XCTAssertNil(value) @@ -1035,18 +1019,7 @@ private actor IteratorWrapper { } } -private final class RefError: Error { - - private let onDeinit: () -> Void - - init(onDeinit: @escaping () -> Void) { - self.onDeinit = onDeinit - } - - deinit { - onDeinit() - } -} +private final class RefError: Error {} @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) extension Task where Success == Never, Failure == Never { diff --git a/Tests/OpenCombineTests/DispatchTests/DispatchQueueSchedulerTests.swift b/Tests/OpenCombineTests/DispatchTests/DispatchQueueSchedulerTests.swift index 918c142e4..c9d7b7469 100644 --- a/Tests/OpenCombineTests/DispatchTests/DispatchQueueSchedulerTests.swift +++ b/Tests/OpenCombineTests/DispatchTests/DispatchQueueSchedulerTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 26.08.2019. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Dispatch import XCTest @@ -186,8 +186,7 @@ final class DispatchQueueSchedulerTests: XCTestCase { makeStride = Stride.init(__guessFromUnknown:) #endif -// riscv64 is not support on Swift 5.7 Toolchain -#if arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) /*|| arch(riscv64)*/ +#if _pointerBitWidth(_64) // 64-bit platforms let minNanoseconds = -0x13B13B13B13B13B0 // Int64.min / 6.5 let maxNanoseconds = 0x2C4EC4EC4EC4EC4D // Int64.max / 2.889 @@ -263,8 +262,7 @@ final class DispatchQueueSchedulerTests: XCTestCase { XCTAssertEqual(Stride.microseconds(2).magnitude, 2_000) XCTAssertEqual(Stride.nanoseconds(2).magnitude, 2) -// riscv64 is not support on Swift 5.7 Toolchain -#if arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) /*|| arch(riscv64)*/ +#if _pointerBitWidth(_64) // 64-bit platforms XCTAssertEqual( Stride.seconds(Double(Int.max) / 1_000_000_000 - 1).magnitude, @@ -293,8 +291,7 @@ final class DispatchQueueSchedulerTests: XCTestCase { } func testStrideFromTooMuchSeconds() { -// riscv64 is not support on Swift 5.7 Toolchain -#if arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) /*|| arch(riscv64)*/ +#if _pointerBitWidth(_64) // 64-bit platforms XCTAssertEqual( Stride.seconds(Double(Int.max) / 1_000_000_000).magnitude, diff --git a/Tests/OpenCombineTests/FoundationTests/JSONDecoderTests.swift b/Tests/OpenCombineTests/FoundationTests/JSONDecoderTests.swift index 953b39bc5..661d671bc 100644 --- a/Tests/OpenCombineTests/FoundationTests/JSONDecoderTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/JSONDecoderTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 10.12.2019. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Foundation import XCTest diff --git a/Tests/OpenCombineTests/FoundationTests/JSONEncoderTests.swift b/Tests/OpenCombineTests/FoundationTests/JSONEncoderTests.swift index 1882a1e51..272f3e6e5 100644 --- a/Tests/OpenCombineTests/FoundationTests/JSONEncoderTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/JSONEncoderTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 10.12.2019. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Foundation import XCTest diff --git a/Tests/OpenCombineTests/FoundationTests/KeyValueObservingPublisherTests.swift b/Tests/OpenCombineTests/FoundationTests/KeyValueObservingPublisherTests.swift index 169ded68e..c950c1b8d 100644 --- a/Tests/OpenCombineTests/FoundationTests/KeyValueObservingPublisherTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/KeyValueObservingPublisherTests.swift @@ -2,7 +2,7 @@ // KeyValueObservingPublisherTests.swift // -#if canImport(ObjectiveC) // TEST_DISCOVERY_CONDITION +#if canImport(ObjectiveC) import Foundation import XCTest diff --git a/Tests/OpenCombineTests/FoundationTests/NotificationCenterTests.swift b/Tests/OpenCombineTests/FoundationTests/NotificationCenterTests.swift index 9b90b1fe7..1f12aced4 100644 --- a/Tests/OpenCombineTests/FoundationTests/NotificationCenterTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/NotificationCenterTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 10.12.2019. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Foundation import XCTest @@ -49,7 +49,7 @@ final class NotificationCenterTests: XCTestCase { var i = 0 - let center = TestNotificationCenter() + let center = NotificationCenter() let name = Notification.Name(rawValue: "testName") let publisher = makePublisher(center, for: name, object: nil) @@ -85,6 +85,7 @@ final class NotificationCenterTests: XCTestCase { XCTAssertEqual(numberOfInputsHistory, expectedNumberOfInputsHistory) } +#if canImport(ObjectiveC) func testBasicBehavior() throws { let center = TestNotificationCenter() let name = Notification.Name(rawValue: "testName") @@ -296,8 +297,10 @@ final class NotificationCenterTests: XCTestCase { .value(note)]) } +#endif + func testRecursivelyReceiveValue() throws { - let center = TestNotificationCenter() + let center = NotificationCenter() let name = Notification.Name(rawValue: "testName") let publisher = makePublisher(center, for: name, object: nil) let tracking = TrackingSubscriberBase( @@ -334,6 +337,7 @@ final class NotificationCenterTests: XCTestCase { .value(note)]) } +#if canImport(ObjectiveC) func testCancelAlreadyCancelled() throws { let center = TestNotificationCenter() let name = Notification.Name(rawValue: "testName") @@ -428,6 +432,61 @@ final class NotificationCenterTests: XCTestCase { ) } +#endif + + func testFiltersNotificationsAndCancelsSubscription() throws { + let center = NotificationCenter() + let name = Notification.Name("testName") + let object = NSObject() + let publisher = makePublisher(center, for: name, object: object) + var subscription: Subscription? + let tracking = TrackingSubscriberBase( + receiveSubscription: { subscription = $0 } + ) + publisher.subscribe(tracking) + + let note = Notification(name: name, object: object) + center.post(note) + XCTAssertEqual(tracking.inputs.count, 0) + + try XCTUnwrap(subscription).request(.max(1)) + center.post(name: Notification.Name("unrelated"), object: object) + center.post(name: name, object: NSObject()) + center.post(name: name, object: nil) + XCTAssertEqual(tracking.inputs.count, 0) + + center.post(note) + center.post(note) + XCTAssertEqual(tracking.history, [.subscription("NotificationCenter Observer"), + .value(note)]) + + try XCTUnwrap(subscription).request(.unlimited) + try XCTUnwrap(subscription).cancel() + try XCTUnwrap(subscription).cancel() + center.post(note) + XCTAssertEqual(tracking.inputs.count, 1) + XCTAssertEqual(tracking.completions.count, 0) + } + + func testRealCenterReleasedAfterCancellation() throws { + weak var weakCenter: NotificationCenter? + var subscription: Subscription? + do { + let center = NotificationCenter() + weakCenter = center + let publisher = makePublisher(center, + for: Notification.Name("testName"), + object: nil) + let tracking = TrackingSubscriberBase( + receiveSubscription: { subscription = $0 } + ) + publisher.subscribe(tracking) + } + XCTAssertNotNil(weakCenter) + try XCTUnwrap(subscription).cancel() + XCTAssertNil(weakCenter) + } + func testEquatable() { let center1 = NotificationCenter() let center2 = NotificationCenter() @@ -474,9 +533,11 @@ private func makePublisher( } #endif +// Corelibs Foundation exposes these methods in extensions that cannot be overridden. +#if canImport(ObjectiveC) /// A simple mock notification center that always sends notifications to **all** /// observers in non-thread safe manner. -private final class TestNotificationCenter: NotificationCenter { +private final class TestNotificationCenter: NotificationCenter, @unchecked Sendable { enum Event { case postNotificationWithName(Notification.Name, Any?, [AnyHashable : Any]?) @@ -555,6 +616,8 @@ private final class TestNotificationCenter: NotificationCenter { } } +#endif + private final class TestObject: NSObject { static let one = TestObject() @@ -562,6 +625,7 @@ private final class TestObject: NSObject { static let two = TestObject() } +#if canImport(ObjectiveC) extension TestNotificationCenter.Event: Equatable { fileprivate static func == (lhs: TestNotificationCenter.Event, rhs: TestNotificationCenter.Event) -> Bool { @@ -626,4 +690,6 @@ extension TestNotificationCenter.Event: CustomStringConvertible { } } +#endif // canImport(ObjectiveC) + #endif // !os(WASI) diff --git a/Tests/OpenCombineTests/FoundationTests/OperationQueueSchedulerTests.swift b/Tests/OpenCombineTests/FoundationTests/OperationQueueSchedulerTests.swift index 50e478884..d92fe5c57 100644 --- a/Tests/OpenCombineTests/FoundationTests/OperationQueueSchedulerTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/OperationQueueSchedulerTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 14.06.2020. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Foundation import XCTest @@ -332,7 +332,7 @@ extension OperationQueueScheduler.SchedulerTimeType: DateBackedSchedulerTimeType @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension OperationQueueScheduler: RunLoopLikeScheduler {} -private final class TestOperationQueue: OperationQueue { +private final class TestOperationQueue: OperationQueue, @unchecked Sendable { enum Event { case progress @@ -374,13 +374,13 @@ private final class TestOperationQueue: OperationQueue { super.addOperations(ops, waitUntilFinished: wait) } - override func addOperation(_ block: @escaping () -> Void) { + override func addOperation(_ block: @escaping @Sendable () -> Void) { history.append(.addBlockOperation(block)) super.addOperation(block) } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - override func addBarrierBlock(_ barrier: @escaping () -> Void) { + override func addBarrierBlock(_ barrier: @escaping @Sendable () -> Void) { history.append(.addBarrierBlock(barrier)) super.addBarrierBlock(barrier) } diff --git a/Tests/OpenCombineTests/FoundationTests/PropertyListDecoderTests.swift b/Tests/OpenCombineTests/FoundationTests/PropertyListDecoderTests.swift index 066eb075f..8dd7ec6f7 100644 --- a/Tests/OpenCombineTests/FoundationTests/PropertyListDecoderTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/PropertyListDecoderTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 10.12.2019. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Foundation import XCTest diff --git a/Tests/OpenCombineTests/FoundationTests/PropertyListEncoderTests.swift b/Tests/OpenCombineTests/FoundationTests/PropertyListEncoderTests.swift index 8a49758cf..d09eb7b55 100644 --- a/Tests/OpenCombineTests/FoundationTests/PropertyListEncoderTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/PropertyListEncoderTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 10.12.2019. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Foundation import XCTest diff --git a/Tests/OpenCombineTests/FoundationTests/RunLoopSchedulerTests.swift b/Tests/OpenCombineTests/FoundationTests/RunLoopSchedulerTests.swift index 4be1b33b3..661eba388 100644 --- a/Tests/OpenCombineTests/FoundationTests/RunLoopSchedulerTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/RunLoopSchedulerTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 14.12.2019. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Foundation import XCTest @@ -79,8 +79,7 @@ final class RunLoopSchedulerTests: XCTestCase { XCTAssertEqual(time.advanced(by: stride2), .init(Date(timeIntervalSinceReferenceDate: 9780))) -// riscv64 is not support on Swift 5.7 Toolchain -#if arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) /*|| arch(riscv64)*/ +#if _pointerBitWidth(_64) // 64-bit platforms XCTAssertEqual(time.advanced(by: .nanoseconds(.max)).date, Date(timeIntervalSinceReferenceDate: 9223382036.854776)) @@ -167,8 +166,7 @@ final class RunLoopSchedulerTests: XCTestCase { XCTAssertEqual(Stride.milliseconds(2).timeInterval, 0.002) XCTAssertEqual(Stride.microseconds(2).timeInterval, 2E-06) XCTAssertEqual(Stride.nanoseconds(2).timeInterval, 2E-09) -// riscv64 is not support on Swift 5.7 Toolchain -#if arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) /*|| arch(riscv64)*/ +#if _pointerBitWidth(_64) // 64-bit platforms XCTAssertEqual(Stride.seconds(Int.max).timeInterval, 9.223372036854776E+18) XCTAssertEqual(Stride.milliseconds(.max).timeInterval, 9.223372036854776E+15) diff --git a/Tests/OpenCombineTests/FoundationTests/TimerPublisherTests.swift b/Tests/OpenCombineTests/FoundationTests/TimerPublisherTests.swift index 6c31e334c..82f79d786 100644 --- a/Tests/OpenCombineTests/FoundationTests/TimerPublisherTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/TimerPublisherTests.swift @@ -5,7 +5,7 @@ // Created by Sergej Jaskiewicz on 23.06.2020. // -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) import Foundation import XCTest diff --git a/Tests/OpenCombineTests/FoundationTests/URLSessionTests.swift b/Tests/OpenCombineTests/FoundationTests/URLSessionTests.swift index 2a6fe2929..589e326ae 100644 --- a/Tests/OpenCombineTests/FoundationTests/URLSessionTests.swift +++ b/Tests/OpenCombineTests/FoundationTests/URLSessionTests.swift @@ -14,7 +14,7 @@ import XCTest import FoundationNetworking #endif -#if !os(WASI) // TEST_DISCOVERY_CONDITION +#if !os(WASI) #if OPENCOMBINE_COMPATIBILITY_TEST import Combine @@ -247,7 +247,7 @@ final class URLSessionTests: XCTestCase { /// A simple mock URLSession that records its history and allows executing /// callbacks synchronously -private class TestURLSession: URLSession { +private class TestURLSession: URLSession, @unchecked Sendable { enum Event: Equatable { case delegateQueue @@ -356,18 +356,18 @@ private class TestURLSession: URLSession { super.invalidateAndCancel() } - override func reset(completionHandler: @escaping () -> Void) { + override func reset(completionHandler: @escaping @Sendable () -> Void) { history.append(.reset) super.reset(completionHandler: completionHandler) } - override func flush(completionHandler: @escaping () -> Void) { + override func flush(completionHandler: @escaping @Sendable () -> Void) { history.append(.flush) super.flush(completionHandler: completionHandler) } override func getTasksWithCompletionHandler( - _ completionHandler: @escaping ([URLSessionDataTask], + _ completionHandler: @escaping @Sendable ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) -> Void ) { @@ -376,7 +376,9 @@ private class TestURLSession: URLSession { } @available(macOS 10.11, iOS 9.0, *) - override func getAllTasks(completionHandler: @escaping ([URLSessionTask]) -> Void) { + override func getAllTasks( + completionHandler: @escaping @Sendable ([URLSessionTask]) -> Void + ) { history.append(.getAllTasks) super.getAllTasks(completionHandler: completionHandler) } @@ -393,7 +395,7 @@ private class TestURLSession: URLSession { override func dataTask( with url: URL, - completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void + completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void ) -> URLSessionDataTask { history.append(.dataTaskWithURLAndCompletion(url)) dataTaskCompletionHandlers.append(completionHandler) @@ -402,7 +404,7 @@ private class TestURLSession: URLSession { override func dataTask( with request: URLRequest, - completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void + completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void ) -> URLSessionDataTask { history.append(.dataTaskWithRequestAndCompletion(request)) dataTaskCompletionHandlers.append(completionHandler) @@ -431,7 +433,7 @@ private class TestURLSession: URLSession { override func uploadTask( with request: URLRequest, fromFile fileURL: URL, - completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void + completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void ) -> URLSessionUploadTask { history.append(.uploadTaskWithRequestFromFileWithCompletion(request, fileURL)) return super.uploadTask(with: request, @@ -442,7 +444,7 @@ private class TestURLSession: URLSession { override func uploadTask( with request: URLRequest, from bodyData: Data?, - completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void + completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void ) -> URLSessionUploadTask { history.append(.uploadTaskWithRequestFromDataWithCompletion(request, bodyData)) return super.uploadTask(with: request, @@ -462,7 +464,7 @@ private class TestURLSession: URLSession { override func downloadTask( with request: URLRequest, - completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void + completionHandler: @escaping @Sendable (URL?, URLResponse?, Error?) -> Void ) -> URLSessionDownloadTask { history.append(.downloadTaskWithRequestAndCompletion(request)) return super.downloadTask(with: request, completionHandler: completionHandler) @@ -470,7 +472,7 @@ private class TestURLSession: URLSession { override func downloadTask( with url: URL, - completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void + completionHandler: @escaping @Sendable (URL?, URLResponse?, Error?) -> Void ) -> URLSessionDownloadTask { history.append(.downloadTaskWithURLAndCompletion(url)) return super.downloadTask(with: url, completionHandler: completionHandler) @@ -478,7 +480,7 @@ private class TestURLSession: URLSession { override func downloadTask( withResumeData resumeData: Data, - completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void + completionHandler: @escaping @Sendable (URL?, URLResponse?, Error?) -> Void ) -> URLSessionDownloadTask { history.append(.downloadTaskWithResumeDataAndCompletion(resumeData)) return super.downloadTask(withResumeData: resumeData, @@ -527,7 +529,7 @@ private class TestURLSession: URLSession { #endif // canImport(Darwin) && !os(watchOS) } -private final class TestURLSessionDataTask: URLSessionDataTask { +private final class TestURLSessionDataTask: URLSessionDataTask, @unchecked Sendable { enum Event: Equatable { case taskIdentifier diff --git a/Tests/OpenCombineTests/Helpers/AssertCrashes.swift b/Tests/OpenCombineTests/Helpers/AssertCrashes.swift index a624bec86..06ab14c3f 100644 --- a/Tests/OpenCombineTests/Helpers/AssertCrashes.swift +++ b/Tests/OpenCombineTests/Helpers/AssertCrashes.swift @@ -9,7 +9,7 @@ import Foundation import XCTest #if canImport(COpenCombineHelpers) -@_implementationOnly import COpenCombineHelpers +internal import COpenCombineHelpers #endif extension XCTest { diff --git a/Tests/OpenCombineTests/Helpers/CommonTests.swift b/Tests/OpenCombineTests/Helpers/CommonTests.swift index 5fd8a4a8b..100dc97d6 100644 --- a/Tests/OpenCombineTests/Helpers/CommonTests.swift +++ b/Tests/OpenCombineTests/Helpers/CommonTests.swift @@ -216,12 +216,6 @@ func unreachable() -> Never { func fromNever(_ resultType: T.Type) -> (Never) -> T { // This is to avoid the 'Will never be executed' warning. - // - // The first variant doesn't produce warnings in Swift 5.1, but doesn't compile - // with early Swift versions. - // - // The second variant compiles with all Swift versions, - // but produces a warning in Swift 5.1. return { (_: Never) -> T in } } diff --git a/Tests/OpenCombineTests/ObservableObjectTests.swift b/Tests/OpenCombineTests/ObservableObjectTests.swift index bc2d0c73b..d21eeb626 100644 --- a/Tests/OpenCombineTests/ObservableObjectTests.swift +++ b/Tests/OpenCombineTests/ObservableObjectTests.swift @@ -334,8 +334,12 @@ private final class ObservedDerivedWithObservedBase: ObservedBase { @Published var subclassPublished2 = 2 } +#if OPENCOMBINE_COMPATIBILITY_TEST @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) +extension NSNumber: @retroactive ObservableObject {} +#else extension NSNumber: ObservableObject {} +#endif @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) private final class ObjCClassSubclass: NSObject, ObservableObject { @@ -343,18 +347,22 @@ private final class ObjCClassSubclass: NSObject, ObservableObject { } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -private class ResilientClassSubclass: JSONDecoder, ObservableObject { +private class ResilientClassSubclass: JSONDecoder, ObservableObject, @unchecked Sendable { @Published var published0 = 10 @Published var published1 = "hello!" } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -private final class ResilientClassSubclass2: ResilientClassSubclass { +private final class ResilientClassSubclass2: ResilientClassSubclass, @unchecked Sendable { @Published var published3 = true } +#if OPENCOMBINE_COMPATIBILITY_TEST @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) +extension JSONEncoder: @retroactive ObservableObject {} +#else extension JSONEncoder: ObservableObject {} +#endif @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) private final class GenericClass: ObservableObject { @@ -388,7 +396,8 @@ private class NSObjectSubclass: NSObject, ObservableObject { @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) private class ResilientClassGenericSubclass : JSONDecoder, - ObservableObject + ObservableObject, + @unchecked Sendable { @Published var value1: Value1 @Published var value2: Value2 @@ -401,7 +410,7 @@ private class ResilientClassGenericSubclass @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) private final class ResilientClassGenericSubclass2 - : ResilientClassGenericSubclass + : ResilientClassGenericSubclass, @unchecked Sendable { @Published var value3 = false } diff --git a/Tests/OpenCombineTests/PublisherTests/CatchTests.swift b/Tests/OpenCombineTests/PublisherTests/CatchTests.swift index 62dba547b..2e122c039 100644 --- a/Tests/OpenCombineTests/PublisherTests/CatchTests.swift +++ b/Tests/OpenCombineTests/PublisherTests/CatchTests.swift @@ -8,7 +8,7 @@ import XCTest #if canImport(COpenCombineHelpers) -@_implementationOnly import COpenCombineHelpers +internal import COpenCombineHelpers #endif #if OPENCOMBINE_COMPATIBILITY_TEST diff --git a/Tests/OpenCombineTests/PublisherTests/CombineLatestTests.swift b/Tests/OpenCombineTests/PublisherTests/CombineLatestTests.swift index 897ebb4ea..0590cce4e 100644 --- a/Tests/OpenCombineTests/PublisherTests/CombineLatestTests.swift +++ b/Tests/OpenCombineTests/PublisherTests/CombineLatestTests.swift @@ -683,7 +683,9 @@ final class CombineLatestTests: XCTestCase { }) .store(in: &subscriptions) - wait(for: [expectation], timeout: 5) + withExtendedLifetime(subscriptions) { + wait(for: [expectation], timeout: 5) + } XCTAssertEqual(result?.0, 1) XCTAssertEqual(result?.1, 2) diff --git a/Tests/OpenCombineTests/PublisherTests/FutureTests.swift b/Tests/OpenCombineTests/PublisherTests/FutureTests.swift index e90cbde19..2ac615c65 100644 --- a/Tests/OpenCombineTests/PublisherTests/FutureTests.swift +++ b/Tests/OpenCombineTests/PublisherTests/FutureTests.swift @@ -20,7 +20,8 @@ final class FutureTests: XCTestCase { private typealias Sut = Future private func assertParent(of futureSubscription: Subscription, isNil: Bool) { - +#if !OPENCOMBINE_COMPATIBILITY_TEST + // Combine does not guarantee the layout of its private subscription types. let parent: Mirror.Child do { parent = try XCTUnwrap( @@ -33,19 +34,13 @@ final class FutureTests: XCTestCase { return } - - // FIXME: This will fail on compatibility test when env is macOS 13 + Xcode 15.1. Can't reproduce this on macOS 12 and macOS 14 - #if OPENCOMBINE_COMPATIBILITY_TEST && os(macOS) - guard ProcessInfo().operatingSystemVersion.majorVersion != 13 else { - return - } - #endif let parentAsSut = parent.value as? Sut if isNil { XCTAssertNil(parentAsSut) } else { XCTAssertNotNil(parentAsSut) } +#endif } func testFutureSuccess() throws { diff --git a/Tests/OpenCombineTests/PublisherTests/MapKeyPathTests.swift b/Tests/OpenCombineTests/PublisherTests/MapKeyPathTests.swift index 68ad0fbac..c3529a41c 100644 --- a/Tests/OpenCombineTests/PublisherTests/MapKeyPathTests.swift +++ b/Tests/OpenCombineTests/PublisherTests/MapKeyPathTests.swift @@ -154,7 +154,7 @@ final class MapKeyPathTests: XCTestCase { { $0.map(\.doubled, \.tripled, \.quadrupled) }) } #else - // on Swift 5.8 + non-Xcode env, the result will sometimes be "\Int." and sometimes be "\Int.doubled" + // Non-Xcode toolchains don't guarantee a stable reflected key-path spelling. func testMapKeyPathReflection() throws { try testReflection(parentInput: Int.self, parentFailure: Never.self, diff --git a/Tests/OpenCombineTests/PublisherTests/SequenceTests.swift b/Tests/OpenCombineTests/PublisherTests/SequenceTests.swift index a4cd324a4..8558e3d59 100644 --- a/Tests/OpenCombineTests/PublisherTests/SequenceTests.swift +++ b/Tests/OpenCombineTests/PublisherTests/SequenceTests.swift @@ -24,10 +24,6 @@ final class SequenceTests: XCTestCase { Result.OCombine.Publisher #endif - // Fix compile issue on Swift 5.8~5.9 - // It should be fixed on Xcode 15.1 with Swift 5.9.2 - private var empty: EmptyCollection { .init() } - func testEmptySequence() { let emptyCounter = Counter(upperBound: 0) @@ -308,7 +304,7 @@ final class SequenceTests: XCTestCase { func testCollectOperatorSpecialization() { XCTAssertEqual(makePublisher(1 ..< 5).collect(), .init([1, 2, 3, 4])) - XCTAssertEqual(makePublisher(empty).collect(), .init([])) + XCTAssertEqual(makePublisher(EmptyCollection()).collect(), .init([])) } func testCompactMapOperatorSpecialization() { @@ -318,19 +314,19 @@ final class SequenceTests: XCTestCase { } func testMinOperatorSpecialization() { - XCTAssertEqual(makePublisher(empty).min(), .init(nil)) + XCTAssertEqual(makePublisher(EmptyCollection()).min(), .init(nil)) XCTAssertEqual(makePublisher([3, 4, 5, -1, 2]).min(), .init(-1)) XCTAssertEqual(makePublisher([3, 4, 5, -1, 2]).min(by: >), .init(5)) } func testMaxOperatorSpecialization() { - XCTAssertEqual(makePublisher(empty).max(), .init(nil)) + XCTAssertEqual(makePublisher(EmptyCollection()).max(), .init(nil)) XCTAssertEqual(makePublisher([3, 4, 5, -1, 2]).max(), .init(5)) XCTAssertEqual(makePublisher([3, 4, 5, -1, 2]).max(by: >), .init(-1)) } func testContainsOperatorSpecialization() { - XCTAssertEqual(makePublisher(empty).contains(12), .init(false)) + XCTAssertEqual(makePublisher(EmptyCollection()).contains(12), .init(false)) XCTAssertEqual(makePublisher(0 ..< 12).contains(12), .init(false)) XCTAssertEqual(makePublisher(0 ... 12).contains(12), .init(true)) @@ -342,7 +338,7 @@ final class SequenceTests: XCTestCase { XCTAssertFalse(try makePublisher(0 ..< 100).tryContains { $0 > 100 }.result.get()) XCTAssertTrue(try makePublisher(99 ..< 200).tryContains { $0 < 100 }.result.get()) XCTAssertFalse( - try makePublisher(empty) + try makePublisher(EmptyCollection()) .tryContains(where: throwing).result.get() ) assertThrowsError( @@ -354,7 +350,7 @@ final class SequenceTests: XCTestCase { func testDropWhileOperatorSpecialization() { XCTAssertEqual(Array(makePublisher(0 ..< 7).drop { $0 < 5 }.sequence), [5, 6]) XCTAssertEqual( - Array(makePublisher(empty).drop { _ in true }.sequence), + Array(makePublisher(EmptyCollection()).drop { _ in true }.sequence), [] ) } @@ -363,7 +359,7 @@ final class SequenceTests: XCTestCase { XCTAssertEqual(Array(makePublisher(0 ..< 4).dropFirst().sequence), [1, 2, 3]) XCTAssertEqual(Array(makePublisher(0 ..< 4).dropFirst(3).sequence), [3]) XCTAssertEqual( - Array(makePublisher(empty).dropFirst(.max).sequence), + Array(makePublisher(EmptyCollection()).dropFirst(.max).sequence), [] ) } @@ -372,7 +368,7 @@ final class SequenceTests: XCTestCase { XCTAssertEqual(makePublisher(1 ..< 9).first { $0.isMultiple(of: 4) }, .init(4)) XCTAssertEqual(makePublisher(1 ..< 9).first { $0.isMultiple(of: 13) }, .init(nil)) XCTAssertEqual( - makePublisher(empty).first { $0.isMultiple(of: 13) }, + makePublisher(EmptyCollection()).first { $0.isMultiple(of: 13) }, .init(nil) ) } @@ -403,24 +399,24 @@ final class SequenceTests: XCTestCase { XCTAssertEqual(Array(makePublisher(0 ..< 10).prefix { $0 < 0 }.sequence), []) XCTAssertEqual( - Array(makePublisher(empty).prefix { $0 < 0 }.sequence), + Array(makePublisher(EmptyCollection()).prefix { $0 < 0 }.sequence), [] ) } func testReduceOperatorSpecialization() { XCTAssertEqual(makePublisher(0 ..< 5).reduce(10, +), .init(20)) - XCTAssertEqual(makePublisher(empty).reduce(1, *), .init(1)) + XCTAssertEqual(makePublisher(EmptyCollection()).reduce(1, *), .init(1)) } func testTryReduceOperatorSpecialization() { XCTAssertEqual(try makePublisher(0 ..< 5).tryReduce(10, +).result.get(), 20) XCTAssertEqual( - try makePublisher(empty).tryReduce(1, *).result.get(), + try makePublisher(EmptyCollection()).tryReduce(1, *).result.get(), 1 ) XCTAssertEqual( - try makePublisher(empty).tryReduce(1, throwing).result.get(), + try makePublisher(EmptyCollection()).tryReduce(1, throwing).result.get(), 1 ) @@ -460,12 +456,12 @@ final class SequenceTests: XCTestCase { func testFirstOperatorSpecialization() { XCTAssertEqual(makePublisher([1, 2, 3]).first(), .init(1)) - XCTAssertEqual(makePublisher(empty).first(), .init(nil)) + XCTAssertEqual(makePublisher(EmptyCollection()).first(), .init(nil)) } func testCountOperatorSpecialization() { XCTAssertEqual(makePublisher(0 ..< .max).count(), Just(.max)) - XCTAssertEqual(makePublisher(empty).count(), Just(0)) + XCTAssertEqual(makePublisher(EmptyCollection()).count(), Just(0)) XCTAssertEqual(makePublisher([1, 1, 1, 1, 1, 1]).count(), Just(6)) XCTAssertEqual( makePublisher([1, 1, 1, 1, 1, 1]) @@ -534,14 +530,14 @@ final class SequenceTests: XCTestCase { func testLastOperatorSpecialization() { XCTAssertEqual(makePublisher([1, 2, 3]).last(), .init(3)) - XCTAssertEqual(makePublisher(empty).last(), .init(nil)) + XCTAssertEqual(makePublisher(EmptyCollection()).last(), .init(nil)) } func testLastWhereOperatorSpecialization() { XCTAssertEqual(makePublisher(1 ..< 9).last { $0.isMultiple(of: 4) }, .init(8)) XCTAssertEqual(makePublisher(1 ..< 9).last { $0.isMultiple(of: 13) }, .init(nil)) XCTAssertEqual( - makePublisher(empty).last { $0.isMultiple(of: 13) }, + makePublisher(EmptyCollection()).last { $0.isMultiple(of: 13) }, .init(nil) ) } diff --git a/Tests/OpenCombineTests/PublisherTests/ZipTests.swift b/Tests/OpenCombineTests/PublisherTests/ZipTests.swift index 1cd3d7358..811d4be24 100644 --- a/Tests/OpenCombineTests/PublisherTests/ZipTests.swift +++ b/Tests/OpenCombineTests/PublisherTests/ZipTests.swift @@ -767,7 +767,9 @@ final class ZipTests: XCTestCase { }) .store(in: &subscriptions) - wait(for: [expectation], timeout: 5) + withExtendedLifetime(subscriptions) { + wait(for: [expectation], timeout: 5) + } XCTAssertEqual(result?.0, 1) XCTAssertEqual(result?.1, 2) diff --git a/utils/discover_tests.py b/utils/discover_tests.py deleted file mode 100644 index 2075a78b6..000000000 --- a/utils/discover_tests.py +++ /dev/null @@ -1,79 +0,0 @@ -""" -Parse test files and generate LinuxMain.swift. - -This script uses simple regular expressions to extract test names from test files. -We don't use --enable-test-discovery because: - * it doesn't work with Swift 5.0 that we still support - * there are other problems with it: https://bugs.swift.org/browse/SR-10783 -""" -import sys - -if sys.version_info < (3, 6, 0): - exit("This script only works with Python 3.6 and newer.") - -import re -from pathlib import Path -from argparse import ArgumentParser - -class Test: - def __init__(self, name, is_async): - self.name = name - self.is_async = is_async - - def __str__(self): - return self.name - - -TEST_METHOD_PATTERN = \ - re.compile(r"func\s*(test\w+)\s*\(\s*\)\s*(async\s*)?(?:throws\s*)?{") -TEST_DISCOVERY_CONDITION_PATTERN = \ - re.compile(r"^#if (.+)\s*\/\/\s*TEST_DISCOVERY_CONDITION\s*$", flags=re.MULTILINE) - -def extract_test_names(test_file): - contents = test_file.read_text() - tests = [Test(match[1], match[2] is not None) for match in TEST_METHOD_PATTERN.finditer(contents)] - condition = TEST_DISCOVERY_CONDITION_PATTERN.search(contents) - return (tests, condition[1] if condition else None) - -def generate_linuxmain(workdir): - workdir = Path(workdir) - tests_dir = workdir / "Tests" - test_files = (tests_dir / "OpenCombineTests").glob("*/*Tests.swift") - - with (tests_dir / "LinuxMain.swift").open(mode="w") as linuxmain: - linuxmain.write("""\ -import XCTest - -@testable import OpenCombineTests - -var tests = [XCTestCaseEntry]() - -""") - for test_file in test_files: - (tests, condition) = extract_test_names(test_file) - if not tests: - continue - if condition: - linuxmain.write(f"#if {condition}\n") - linuxmain.write(f"let allTests_{test_file.stem} = [\n") - for test in tests: - if test.is_async: - linuxmain.write(f" (\"{test}\", asyncTest({test_file.stem}.{test})),\n") - else: - linuxmain.write(f" (\"{test}\", {test_file.stem}.{test}),\n") - linuxmain.write("]\n") - linuxmain.write(f"tests.append(testCase(allTests_{test_file.stem}))\n") - if condition: - linuxmain.write("#endif\n") - linuxmain.write("\n") - - linuxmain.write("XCTMain(tests)") - - -if __name__ == "__main__": - parser = ArgumentParser(description="Generates LinuxMain.swift for OpenCombine tests") - parser.add_argument("workdir", type=Path, nargs="?", - help="The root directory of the OpenCombine Swift package") - args = parser.parse_args() - workdir = args.workdir or Path.cwd() - generate_linuxmain(workdir) diff --git a/utils/gyb.py b/utils/gyb.py index 274fd7324..159532ead 100755 --- a/utils/gyb.py +++ b/utils/gyb.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # GYB: Generate Your Boilerplate (improved names welcome; at least # this one's short). See -h output for instructions diff --git a/utils/lint.sh b/utils/lint.sh new file mode 100644 index 000000000..d65abcbe4 --- /dev/null +++ b/utils/lint.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +set -euo pipefail + +base_ref=${1:?Usage: bash utils/lint.sh BASE_REF} +repo_root=$(git rev-parse --show-toplevel) +baseline_dir=$(mktemp -d) +trap 'rm -rf "$baseline_dir"' EXIT + +# Keep existing violations in the base revision from blocking unrelated changes. +git archive "$base_ref" | tar -x -C "$baseline_dir" +( + cd "$baseline_dir" + swiftlint lint --strict --no-cache --write-baseline baseline.json > lint.log 2>&1 || { + status=$? + if [ "$status" -ne 2 ] || [ ! -s baseline.json ]; then + cat lint.log + exit "$status" + fi + } +) + +python3 - "$baseline_dir" "$repo_root" <<'PY' +import json +import sys +from pathlib import Path + +baseline_dir = Path(sys.argv[1]).resolve() +repo_root = Path(sys.argv[2]).resolve() +baseline_path = baseline_dir / "baseline.json" +violations = json.loads(baseline_path.read_text()) +for violation in violations: + location = violation["violation"]["location"] + location["file"] = location["file"].replace( + baseline_dir.as_uri() + "/", repo_root.as_uri() + "/", 1 + ) +baseline_path.write_text(json.dumps(violations)) +PY + +cd "$repo_root" +swiftlint lint --strict --no-cache --baseline "$baseline_dir/baseline.json" From fdaf48cf007c25e81aa0566984c12e85e8446947 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 27 Sep 2026 19:40:10 +0800 Subject: [PATCH 2/3] Install SwiftLint on the macOS CI runner --- .github/workflows/swiftlint.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/swiftlint.yml b/.github/workflows/swiftlint.yml index f4143358c..e951eb28b 100644 --- a/.github/workflows/swiftlint.yml +++ b/.github/workflows/swiftlint.yml @@ -20,6 +20,8 @@ jobs: uses: OpenSwiftUIProject/setup-xcode@v2 with: xcode-version: "26.6" + - name: Install SwiftLint + run: brew install swiftlint - name: Check new SwiftLint violations env: BASE_SHA: ${{ github.event.pull_request.base.sha }} From ee8fb563d8cb49f628b92dd32523a5f70b4a8211 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 27 Sep 2026 19:47:44 +0800 Subject: [PATCH 3/3] Install curl for coverage uploads in Swift containers --- .github/workflows/ubuntu.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 07035b578..abcf5a926 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -23,6 +23,10 @@ jobs: container: swift:${{ matrix.swift_version }}-${{ matrix.os_name }} steps: - uses: actions/checkout@v6 + - name: Install coverage upload dependencies + run: | + apt-get update + apt-get install -y --no-install-recommends curl - name: Building and running tests in debug mode with coverage run: | swift test \