Skip to content
Open
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
18 changes: 11 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ concurrency:

jobs:
package:
name: Package build (macOS, ${{ matrix.traits.name }})
name: Package tests (macOS, ${{ matrix.traits.name }})
runs-on: macos-15
strategy:
matrix:
Expand All @@ -20,16 +20,20 @@ jobs:
- { name: "without DependencyInjection", flags: "--disable-default-traits" }
steps:
- uses: actions/checkout@v4
- name: Build
run: swift build ${{ matrix.traits.flags }}
- name: Run tests
run: swift test ${{ matrix.traits.flags }}

package-ios:
name: Package build (iOS Simulator)
name: Package tests (iOS Simulator)
runs-on: macos-15
steps:
- uses: actions/checkout@v4
- name: Build
- name: Run tests
run: |
xcodebuild build \
# Use whichever iPhone simulator the runner's Xcode provides
UDID=$(xcrun simctl list devices available -j \
| jq -r '[.devices | to_entries[] | select(.key | contains("iOS")) | .value[] | select(.name | startswith("iPhone"))][0].udid')
echo "Simulator: $UDID"
xcodebuild test \
-scheme DeallocTests \
-destination 'generic/platform=iOS Simulator'
-destination "id=$UDID"
6 changes: 6 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ let package = Package(
)
]
),
.testTarget(
name: "DeallocTestsTests",
dependencies: [
"DeallocTests"
]
),
],
swiftLanguageModes: [.v6]
)
20 changes: 20 additions & 0 deletions Sources/DeallocTests/Diagnostics/DurationText.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//
// DurationText.swift
// DeallocTests
//
// Copyright © 2026 STRV. All rights reserved.
//

enum DurationText {
static func describe(_ duration: Duration) -> String {
let (seconds, attoseconds) = duration.components
let milliseconds = seconds * 1000 + attoseconds / 1_000_000_000_000_000

guard milliseconds >= 1000 else {
return "\(milliseconds) ms"
}

let tenths = milliseconds / 100
return tenths % 10 == 0 ? "\(tenths / 10) sec" : "\(tenths / 10).\(tenths % 10) sec"
}
}
17 changes: 17 additions & 0 deletions Sources/DeallocTests/Diagnostics/LeakReport.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//
// LeakReport.swift
// DeallocTests
//
// Copyright © 2026 STRV. All rights reserved.
//

struct LeakReport: Sendable {
let typeName: String
let timeout: Duration

var message: String {
"\(typeName) was not deallocated within \(DurationText.describe(timeout))."
+ " Something still holds a strong reference to it: look for closures capturing self, "
+ "delegates that aren't weak, timers, notification observers and long-running tasks or subscriptions."
}
}
19 changes: 19 additions & 0 deletions Sources/DeallocTests/Diagnostics/TypeNames.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//
// TypeNames.swift
// DeallocTests
//
// Copyright © 2026 STRV. All rights reserved.
//

import Foundation

enum TypeNames {
static func readableName(of object: AnyObject) -> String {
readableName(of: type(of: object))
}

static func readableName(of type: Any.Type) -> String {
String(reflecting: type)
.replacingOccurrences(of: #"\(unknown context at \$[0-9a-fA-F]+\)\."#, with: "", options: .regularExpression)
}
}
43 changes: 43 additions & 0 deletions Sources/DeallocTests/Expectation/DeallocationTracker.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//
// DeallocationTracker.swift
// DeallocTests
//
// Copyright © 2026 STRV. All rights reserved.
//

@MainActor
final class DeallocationTracker {
private struct TrackedObject {
weak var object: AnyObject?
let typeName: String
let location: TestSourceLocation
}

private var trackedObjects = [TrackedObject]()

func track(_ object: AnyObject, at location: TestSourceLocation) {
trackedObjects.append(
TrackedObject(object: object, typeName: TypeNames.readableName(of: object), location: location)
)
}

func verifyDeallocation(timeout: Duration) async {
let objects = trackedObjects
trackedObjects.removeAll()

_ = await Polling.waitUntil(timeout: timeout) {
!objects.contains { $0.object != nil }
}

guard !Task.isCancelled else {
return
}

for trackedObject in objects where trackedObject.object != nil {
reportIssue(
LeakReport(typeName: trackedObject.typeName, timeout: timeout).message,
at: trackedObject.location
)
}
}
}
59 changes: 59 additions & 0 deletions Sources/DeallocTests/Expectation/ExpectDeallocation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//
// ExpectDeallocation.swift
// DeallocTests
//
// Copyright © 2026 STRV. All rights reserved.
//

/// Creates an object, runs its lifecycle, releases it and checks that it deallocates.
///
/// Works in Swift Testing and XCTest. A leak is reported at the line that calls this function.
///
/// ```swift
/// @Test func secondScreenDoesNotLeak() async {
/// await expectDeallocation(.present) {
/// coordinator.createSecondViewController()
/// }
/// }
/// ```
///
/// - Parameters:
/// - lifecycle: What happens with the object before it's released, e.g. `.present` for a view controller
/// - timeout: How long to wait for the object to deallocate
/// - afterRelease: Runs after the object is released and before the check, e.g. to release cached instances
/// - makeObject: Creates the tested object. Don't keep any other reference to it.
@MainActor
public func expectDeallocation<Object: AnyObject>(
_ lifecycle: Lifecycle<Object> = .none,
timeout: Duration = .seconds(2),
afterRelease: @MainActor () async -> Void = {},
fileID: StaticString = #fileID,
filePath: StaticString = #filePath,
line: UInt = #line,
column: UInt = #column,
of makeObject: @MainActor () async throws -> Object
) async rethrows {
let location = TestSourceLocation(fileID: fileID, filePath: filePath, line: line, column: column)
let tracker = DeallocationTracker()

let didRunLifecycle = try await createAndRun(makeObject, lifecycle: lifecycle, tracker: tracker, location: location)
await afterRelease()

guard didRunLifecycle else {
return
}

await tracker.verifyDeallocation(timeout: timeout)
}

@MainActor
private func createAndRun<Object: AnyObject>(
_ makeObject: @MainActor () async throws -> Object,
lifecycle: Lifecycle<Object>,
tracker: DeallocationTracker,
location: TestSourceLocation
) async rethrows -> Bool {
let object = try await makeObject()
tracker.track(object, at: location)
return await lifecycle.run(object, location)
}
49 changes: 49 additions & 0 deletions Sources/DeallocTests/Expectation/IssueReporting.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//
// IssueReporting.swift
// DeallocTests
//
// Copyright © 2026 STRV. All rights reserved.
//

import XCTest

#if canImport(Testing)
import Testing
#endif

struct TestSourceLocation: Sendable {
let fileID: StaticString
let filePath: StaticString
let line: UInt
let column: UInt
}

func reportIssue(_ message: String, at location: TestSourceLocation) {
guard !Task.isCancelled else {
return
}

#if canImport(Testing)
if Test.current != nil {
recordSwiftTestingIssue(message, at: location)
return
}
#endif

XCTFail(message, file: location.filePath, line: location.line)
}

#if canImport(Testing)

private func recordSwiftTestingIssue(_ message: String, at location: TestSourceLocation) {
let sourceLocation = SourceLocation(
fileID: String(describing: location.fileID),
filePath: String(describing: location.filePath),
line: Int(location.line),
column: Int(location.column)
)

Issue.record(Comment(rawValue: message), sourceLocation: sourceLocation)
}

#endif
Loading
Loading