From 55df7f9caeb37f830f4e8793a8e38a1d178ac407 Mon Sep 17 00:00:00 2001 From: Philipp Zagar Date: Wed, 6 Dec 2023 11:32:34 -0800 Subject: [PATCH] Add tests and incorporate review --- .../Dependencies/DependencyCollection.swift | 2 +- .../DependencyBuilderTests.swift | 47 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 Tests/SpeziTests/DependenciesTests/DependencyBuilderTests.swift diff --git a/Sources/Spezi/Dependencies/DependencyCollection.swift b/Sources/Spezi/Dependencies/DependencyCollection.swift index 2cb92539..547b0d93 100644 --- a/Sources/Spezi/Dependencies/DependencyCollection.swift +++ b/Sources/Spezi/Dependencies/DependencyCollection.swift @@ -24,7 +24,7 @@ public struct DependencyCollection: DependencyDeclaration { /// - Parameters: /// - type: The generic type resulting from the passed closure, has to conform to ``Module``. /// - singleEntry: Closure returning a dependency conforming to ``Module``, stored within the ``DependencyCollection``. - public init(for type: Dependency.Type = Dependency.self, singleEntry: (() -> Dependency)? = nil) { + public init(for type: Dependency.Type = Dependency.self, singleEntry: @escaping (() -> Dependency)) { self.init(DependencyContext(for: type, defaultValue: singleEntry)) } diff --git a/Tests/SpeziTests/DependenciesTests/DependencyBuilderTests.swift b/Tests/SpeziTests/DependenciesTests/DependencyBuilderTests.swift new file mode 100644 index 00000000..b13c2d44 --- /dev/null +++ b/Tests/SpeziTests/DependenciesTests/DependencyBuilderTests.swift @@ -0,0 +1,47 @@ +// +// This source file is part of the Stanford Spezi open-source project +// +// SPDX-FileCopyrightText: 2023 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Spezi +import XCTRuntimeAssertions + +private protocol ExampleTypeConstraint: Module {} + +private final class ExampleDependencyModule: ExampleTypeConstraint {} + +@resultBuilder +private enum ExampleDependencyBuilder: DependencyCollectionBuilder { + /// An auto-closure expression, providing the default dependency value, building the ``DependencyCollection``. + public static func buildExpression(_ expression: @escaping @autoclosure () -> L) -> DependencyCollection { + DependencyCollection(singleEntry: expression) + } +} + +private class ExampleModule: Module { + @Dependency var dependencies: [any Module] + + + public init( + @ExampleDependencyBuilder _ dependencies: () -> DependencyCollection + ) { + self._dependencies = Dependency(dependencies) + } +} + +private class ExampleConfiguration { + static let exampleModule = ExampleModule { + ExampleDependencyModule() + } +} + + +final class DependencyBuilderTests: XCTestCase { + func testDependencyBuilder() throws { + XCTAssertEqual(ExampleConfiguration.exampleModule.dependencies.count, 1) + _ = try XCTUnwrap(ExampleConfiguration.exampleModule.dependencies[0] as? ExampleDependencyModule) + } +}