Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swift Testing Implementation #6

Merged
merged 12 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
41 changes: 38 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,16 @@ let package = Package(
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "TestableCombinePublishers",
targets: ["TestableCombinePublishers"]),
targets: ["TestableCombinePublishers"]
),
.library(
name: "SwiftTestingTestableCombinePublihers",
ethan-vanheerden marked this conversation as resolved.
Show resolved Hide resolved
targets: ["SwiftTestingTestableCombinePublishers"]
),
.library(
name: "TestableCombinePublishersUtility",
targets: ["TestableCombinePublishersUtility"]
),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
Expand All @@ -21,12 +30,38 @@ let package = Package(
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "TestableCombinePublishers",
dependencies: [],
dependencies: ["TestableCombinePublishersUtility"],
path: "Sources/TestableCombinePublishers",
linkerSettings: [
.linkedFramework("XCTest")
]),
.target(
name: "SwiftTestingTestableCombinePublishers",
dependencies: ["TestableCombinePublishersUtility"],
path: "Sources/SwiftTestingTestableCombinePublishers",
linkerSettings: [
.linkedFramework("Testing")
]
),
.target(
name: "TestableCombinePublishersUtility",
dependencies: [],
path: "Sources/TestableCombinePublishersUtility"
),
.testTarget(
name: "TestableCombinePublishersTests",
dependencies: ["TestableCombinePublishers"]),
dependencies: ["TestableCombinePublishers"],
path: "Tests/TestableCombinePublishersTests"
),
.testTarget(
name: "SwiftTestingTestableCombinePublishersTests",
dependencies: ["SwiftTestingTestableCombinePublishers"],
path: "Tests/SwiftTestingTestableCombinePublishersTests"
),
.testTarget(
name: "TestableCombinePublishersUtilityTests",
dependencies: ["TestableCombinePublishersUtility"],
path: "Tests/TestableCombinePublishersUtilityTests"
),
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//
// SwiftTestingExpectation.swift
// TestableCombinePublishers
//
// Created by Ethan van Heerden on 11/15/24.
//

import Foundation
import Testing

/// The Swift Testing version of an `XCTestExpectation`.
final class SwiftTestingExpectation {
let id: UUID
let description: String
private let expectedFulfillmentCount: Int
let isInverted: Bool
let sourceLocation: SourceLocation
private var actualFulfillmentCount: Int = 0

init(id: UUID = UUID(),
description: String,
expectedFulfillmentCount: Int = 1,
isInverted: Bool = false,
sourceLocation: SourceLocation) {
self.id = id
self.description = description
self.expectedFulfillmentCount = expectedFulfillmentCount
self.isInverted = isInverted
self.sourceLocation = sourceLocation
}

func fulfill() {
actualFulfillmentCount += 1
}
ethan-vanheerden marked this conversation as resolved.
Show resolved Hide resolved

var isFulfilled: Bool {
return actualFulfillmentCount == expectedFulfillmentCount
}
}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import Combine
import Foundation
import XCTest
import TestableCombinePublishersUtility

/// Provides a convenient way for `Publisher`s to be unit tested.
/// To use this, you can start by typing `expect` on any `Publisher` type.
Expand Down
57 changes: 57 additions & 0 deletions Sources/TestableCombinePublishersUtility/withTimeout.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//
// withTimeout.swift
// TestableCombinePublishers
//
// Created by Albert Bori on 11/15/24.
//

import Foundation

/// Invokes the block of code. If the timeout period is surpassed before the block of code is complete, a ``TimeoutError`` is thrown.
/// Note: This does not cancel the current Task if a timeout occurs.
/// - Parameters:
/// - seconds: The number of seconds that must pass before the task is cancelled.
/// - operation: The block of code to execute before the timeout. Note that this block requires cooperative cancellation. (Proactive checking for cancellation)
/// - onTimeout: An optional closure to be fired just before the timeout error is thrown back to callers. Use this to help with cooperative cancellation, if needed. For example, if you're storing async continuations, you can use this to complete them.
/// - Throws: ``TimeoutError`` if the timeout period is expired, ``NoTimeoutTaskResultError`` if something prevents the timeout functionality from working properly, or ``InvalidTimeoutError`` if the provided timeout interval is not greater than zero.
/// - Returns: The block's result, if not ``Void``
public func withTimeout<OperationResult>(
seconds: TimeInterval,
operation: @escaping @Sendable () async throws -> OperationResult,
onTimeout: @escaping @Sendable () async throws -> Void = { }
) async throws -> OperationResult {
return try await withThrowingTaskGroup(of: OperationResult.self) { group in
// Start actual work.
group.addTask {
try await operation()
}
// Start timeout child task.
group.addTask {
guard seconds > 0 else { throw InvalidTimeoutError() }
try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
try Task.checkCancellation()
// We’ve reached the timeout.
throw TimeoutError()
}
// First finished child task wins, cancel the other task.
do {
guard let result = try await group.next() else {
throw NoTimeoutTaskResultError()
}
group.cancelAll() // Cancels timeout task
return result
} catch let error as TimeoutError {
try await onTimeout()
throw error // Automatically cancels all group tasks
}
}
}

/// Thrown when ``withTimeout(seconds:operation:)`` reaches its limit without completing the code in the block
public struct TimeoutError: Error { }

/// Thrown when ``withTimeout(seconds:operation:)`` is called and the result of the main code block fails to return a result or throw an error.
public struct NoTimeoutTaskResultError: Error { }

/// Thrown when the provided timeout value is not in the future.
public struct InvalidTimeoutError: Error { }
30 changes: 30 additions & 0 deletions Tests/SwiftTestingTestableCombinePublishersTests/ExampleTest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//
// ExampleTest.swift
// TestableCombinePublishers
//
// Created by Ethan van Heerden on 11/15/24.
//

import Combine
import Testing

struct ExampleTest {

@Test func fail() async {
await withKnownIssue() {
let publisher = CurrentValueSubject<String, Error>("foo")
await publisher
.expect("bar")
.expectSuccess()
.waitForExpectations(timeout: 1)
}
}

@Test func pass() async {
let publisher = ["baz"].publisher
await publisher
.expect("baz")
.expectSuccess()
.waitForExpectations(timeout: 1)
}
}
Loading