Skip to content

Commit

Permalink
Add #Preview and @Test traits for overriding dependencies (#274)
Browse files Browse the repository at this point in the history
* Add `#Preview` and `@Test` traits for overriding dependencies

* wip

* wip

* wip

* wip

* Fix

* wip

* docs updates

* wip

* wip

* wip

* Update Sources/DependenciesTestSupport/TestTrait.swift

* Update README.md

* Update Sources/Dependencies/Documentation.docc/Articles/QuickStart.md

* Update Sources/Dependencies/Documentation.docc/Articles/Testing.md

* Update Sources/Dependencies/Documentation.docc/Articles/UsingDependencies.md

* wip

* A few renames

* wip

---------

Co-authored-by: Brandon Williams <[email protected]>
  • Loading branch information
stephencelis and mbrandonw authored Sep 12, 2024
1 parent 9d1e15f commit 5361983
Show file tree
Hide file tree
Showing 30 changed files with 476 additions and 253 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jobs:
strategy:
matrix:
config: ['debug', 'release']
xcode: ['15.4']
xcode: ['15.4', '16_beta_6']
steps:
- uses: actions/checkout@v4
- name: Select Xcode ${{ matrix.xcode }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/xctest-dynamic-overlay",
"state" : {
"revision" : "3fcc3f21695ad5bb889a024b1b046d61bebb1ef3",
"version" : "1.3.0"
"revision" : "bc2a151366f2cd0e347274544933bc2acb00c9fe",
"version" : "1.4.0"
}
}
],
Expand Down
6 changes: 3 additions & 3 deletions Package.resolved
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"originHash" : "583c00d70f39319a7eca67f614e30ccaab233ad9a104a40007e982cf4584d4d6",
"originHash" : "b70d24a284d4a26856cfef0d2ef69b0e2326a2fa8a91e22c08eba0cad0f59bcd",
"pins" : [
{
"identity" : "combine-schedulers",
Expand Down Expand Up @@ -78,8 +78,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/xctest-dynamic-overlay",
"state" : {
"branch" : "test-case-parameterization",
"revision" : "be48dda989581f65f82e09041b11e12da837c49d"
"revision" : "bc2a151366f2cd0e347274544933bc2acb00c9fe",
"version" : "1.4.0"
}
}
],
Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ let package = Package(
.package(url: "https://github.com/pointfreeco/combine-schedulers", from: "1.0.2"),
.package(url: "https://github.com/pointfreeco/swift-clocks", from: "1.0.4"),
.package(url: "https://github.com/pointfreeco/swift-concurrency-extras", from: "1.0.0"),
.package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.3.0"),
.package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.4.0"),
.package(url: "https://github.com/swiftlang/swift-syntax", "509.0.0"..<"601.0.0-prerelease"),
],
targets: [
Expand Down
13 changes: 12 additions & 1 deletion [email protected]
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ let package = Package(
name: "DependenciesMacros",
targets: ["DependenciesMacros"]
),
.library(
name: "DependenciesTestSupport",
targets: ["DependenciesTestSupport"]
),
],
dependencies: [
.package(url: "https://github.com/pointfreeco/combine-schedulers", from: "1.0.2"),
.package(url: "https://github.com/pointfreeco/swift-clocks", from: "1.0.4"),
.package(url: "https://github.com/pointfreeco/swift-concurrency-extras", from: "1.0.0"),
.package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.3.0"),
.package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.4.0"),
.package(url: "https://github.com/swiftlang/swift-syntax", "509.0.0"..<"601.0.0-prerelease"),
],
targets: [
Expand All @@ -45,11 +49,18 @@ let package = Package(
.product(name: "XCTestDynamicOverlay", package: "xctest-dynamic-overlay"),
]
),
.target(
name: "DependenciesTestSupport",
dependencies: [
"Dependencies",
]
),
.testTarget(
name: "DependenciesTests",
dependencies: [
"Dependencies",
"DependenciesMacros",
"DependenciesTestSupport",
.product(name: "IssueReportingTestSupport", package: "xctest-dynamic-overlay"),
]
),
Expand Down
51 changes: 28 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,17 @@ is a good chance you can immediately make use of one. If you are using `Date()`,
this library.

```swift
final class FeatureModel: ObservableObject {
@Observable
final class FeatureModel {
var items: [Item] = []

@ObservationIgnored
@Dependency(\.continuousClock) var clock // Controllable way to sleep a task
@ObservationIgnored
@Dependency(\.date.now) var now // Controllable way to ask for current date
@ObservationIgnored
@Dependency(\.mainQueue) var mainQueue // Controllable scheduling on main queue
@ObservationIgnored
@Dependency(\.uuid) var uuid // Controllable UUID creation

// ...
Expand All @@ -96,16 +103,17 @@ Once your dependencies are declared, rather than reaching out to the `Date()`, `
directly, you can use the dependency that is defined on your feature's model:

```swift
final class FeatureModel: ObservableObject {
@Observable
final class FeatureModel {
// ...

func addButtonTapped() async throws {
try await self.clock.sleep(for: .seconds(1)) // 👈 Don't use 'Task.sleep'
self.items.append(
try await clock.sleep(for: .seconds(1)) // 👈 Don't use 'Task.sleep'
items.append(
Item(
id: self.uuid(), // 👈 Don't use 'UUID()'
id: uuid(), // 👈 Don't use 'UUID()'
name: "",
createdAt: self.now // 👈 Don't use 'Date()'
createdAt: now // 👈 Don't use 'Date()'
)
)
}
Expand All @@ -120,23 +128,22 @@ inside the `addButtonTapped` method, you can use the [`withDependencies`][withde
function to override any dependencies for the scope of one single test. It's as easy as 1-2-3:

```swift
func testAdd() async throws {
let model = withDependencies {
@Test
func add() async throws {
withDependencies {
// 1️⃣ Override any dependencies that your feature uses.
$0.clock = ImmediateClock()
$0.clock = .immediate
$0.date.now = Date(timeIntervalSinceReferenceDate: 1234567890)
$0.uuid = .incrementing
} operation: {
// 2️⃣ Construct the feature's model
FeatureModel()
}

// 3️⃣ The model now executes in a controlled environment of dependencies,
// and so we can make assertions against its behavior.
try await model.addButtonTapped()
XCTAssertEqual(
model.items,
[
#expect(
model.items == [
Item(
id: UUID(uuidString: "00000000-0000-0000-0000-000000000000")!,
name: "",
Expand All @@ -158,19 +165,17 @@ But, controllable dependencies aren't only useful for tests. They can also be us
previews. Suppose the feature above makes use of a clock to sleep for an amount of time before
something happens in the view. If you don't want to literally wait for time to pass in order to see
how the view changes, you can override the clock dependency to be an "immediate" clock using the
[`withDependencies`][withdependencies-docs] helper:
`.dependencies` preview trait:

```swift
struct Feature_Previews: PreviewProvider {
static var previews: some View {
FeatureView(
model: withDependencies {
$0.clock = ImmediateClock()
} operation: {
FeatureModel()
}
)
#Preview(
traits: .dependencies {
$0.continuousClock = .immediate
}
) {
// All access of '@Dependency(\.continuousClock)' in this preview will
// use an immediate clock.
FeatureView(model: FeatureModel())
}
```

Expand Down
17 changes: 13 additions & 4 deletions Sources/Dependencies/Dependency.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@
/// an observable object:
///
/// ```swift
/// final class FeatureModel: ObservableObject {
/// @Observable
/// final class FeatureModel {
/// @ObservationIgnored
/// @Dependency(\.apiClient) var apiClient
/// @ObservationIgnored
/// @Dependency(\.continuousClock) var clock
/// @ObservationIgnored
/// @Dependency(\.uuid) var uuid
///
/// // ...
Expand All @@ -18,7 +22,8 @@
/// Or, if you are using [the Composable Architecture][tca]:
///
/// ```swift
/// struct Feature: ReducerProtocol {
/// @Reducer
/// struct Feature {
/// @Dependency(\.apiClient) var apiClient
/// @Dependency(\.continuousClock) var clock
/// @Dependency(\.uuid) var uuid
Expand Down Expand Up @@ -108,7 +113,9 @@
/// reflect:
///
/// ```swift
/// final class FeatureModel: ObservableObject {
/// @Observable
/// final class FeatureModel {
/// @ObservationIgnored
/// @Dependency(\.date) var date
///
/// // ...
Expand Down Expand Up @@ -158,7 +165,9 @@ extension Dependency {
/// One can access the dependency using this property wrapper:
///
/// ```swift
/// final class FeatureModel: ObservableObject {
/// @Observable
/// final class FeatureModel {
/// @ObservationIgnored
/// @Dependency(Settings.self) var settings
///
/// // ...
Expand Down
5 changes: 3 additions & 2 deletions Sources/Dependencies/DependencyKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,14 +162,15 @@ extension DependencyKey {
/// ``TestDependencyKey``.
public static var previewValue: Value { Self.liveValue }

/// A default implementation that provides the ``previewValue`` to XCTest runs (or ``liveValue``,
/// A default implementation that provides the ``previewValue`` to test runs (or ``liveValue``,
/// if no preview value is implemented), but will trigger a test failure when accessed.
///
/// To prevent test failures, explicitly override the dependency in any tests in which it is
/// accessed:
///
/// ```swift
/// func testFeatureThatUsesMyDependency() {
/// @Test
/// func featureThatUsesMyDependency() {
/// withDependencies {
/// $0.myDependency = .mock // Override dependency
/// } operation: {
Expand Down
26 changes: 24 additions & 2 deletions Sources/Dependencies/DependencyValues.swift
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,11 @@ public struct DependencyValues: Sendable {
#endif
}

package init(context: DependencyContext) {
self.init()
self.context = context
}

@_disfavoredOverload
public subscript<Key: TestDependencyKey>(type: Key.Type) -> Key.Value {
get { self[type] }
Expand Down Expand Up @@ -356,6 +361,8 @@ private let defaultContext: DependencyContext = {

@_spi(Internals)
public final class CachedValues: @unchecked Sendable {
@TaskLocal static var isAccessingCachedDependencies = false

public struct CacheKey: Hashable, Sendable {
let id: TypeIdentifier
let context: DependencyContext
Expand Down Expand Up @@ -397,9 +404,24 @@ public final class CachedValues: @unchecked Sendable {
case .live:
value = (key as? any DependencyKey.Type)?.liveValue as? Key.Value
case .preview:
value = Key.previewValue
if !CachedValues.isAccessingCachedDependencies {
value = CachedValues.$isAccessingCachedDependencies.withValue(true) {
previewValues.withValue { $0[key] }
}
} else {
value = Key.previewValue
}
case .test:
value = Key.testValue
if !CachedValues.isAccessingCachedDependencies,
case let .swiftTesting(.some(testing)) = TestContext.current,
let testValues = testValuesByTestID.withValue({ $0[testing.test.id.rawValue] })
{
value = CachedValues.$isAccessingCachedDependencies.withValue(true) {
testValues[key]
}
} else {
value = Key.testValue
}
}

guard let value
Expand Down
4 changes: 3 additions & 1 deletion Sources/Dependencies/DependencyValues/Date.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ extension DependencyValues {
/// wrapper to the generator's ``DateGenerator/now`` property:
///
/// ```swift
/// final class FeatureModel: ObservableObject {
/// @Observable
/// final class FeatureModel {
/// @ObservationIgnored
/// @Dependency(\.date.now) var now
/// // ...
/// }
Expand Down
4 changes: 3 additions & 1 deletion Sources/Dependencies/DependencyValues/Locale.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ extension DependencyValues {
/// wrapper to the property:
///
/// ```swift
/// final class FeatureModel: ObservableObject {
/// @Observable
/// final class FeatureModel {
/// @ObservationIgnored
/// @Dependency(\.locale) var locale
/// // ...
/// }
Expand Down
21 changes: 12 additions & 9 deletions Sources/Dependencies/DependencyValues/MainQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,28 @@
/// For example, you could introduce controllable timing to an observable object model that
/// counts the number of seconds it's onscreen:
///
/// ```
/// final class TimerModel: ObservableObject {
/// @Published var elapsed = 0
/// ```swift
/// @Observable
/// final class TimerModel {
/// var elapsed = 0
///
/// @ObservationIgnored
/// @Dependency(\.mainQueue) var mainQueue
///
/// @MainActor
/// func onAppear() async {
/// for await _ in self.mainQueue.timer(interval: .seconds(1)) {
/// self.elapsed += 1
/// for await _ in mainQueue.timer(interval: .seconds(1)) {
/// elapsed += 1
/// }
/// }
/// }
/// ```
///
/// And you could test this model by overriding its main queue with a test scheduler:
///
/// ```
/// func testFeature() {
/// ```swift
/// @Test
/// func feature() {
/// let mainQueue = DispatchQueue.test
/// let model = withDependencies {
/// $0.mainQueue = mainQueue.eraseToAnyScheduler()
Expand All @@ -40,10 +43,10 @@
///
/// Task { await model.onAppear() }
///
/// mainQueue.advance(by: .seconds(1))
/// await mainQueue.advance(by: .seconds(1))
/// XCTAssertEqual(model.elapsed, 1)
///
/// mainQueue.advance(by: .seconds(4))
/// await mainQueue.advance(by: .seconds(4))
/// XCTAssertEqual(model.elapsed, 5)
/// }
/// ```
Expand Down
Loading

0 comments on commit 5361983

Please sign in to comment.