From 845d11a3bd17138a9fa902980637cf4ecbc82686 Mon Sep 17 00:00:00 2001 From: Philippe Hausler Date: Mon, 31 Jan 2022 15:28:17 -0800 Subject: [PATCH] Marble diagram based testing (#30) * First draft at marble diagram based tests * Correct indefinite marble runs, support grouping, and properly handle any number of inputs (by the result builder construction) * enhance isolation of diagrams with fileprivate --- .../Support/ManualClock.swift | 4 +- .../Support/MarbleDiagram.swift | 321 ++++++++++++++++++ .../Support/Validator.swift | 55 ++- .../AsyncAlgorithmsTests/TestValidator.swift | 8 + 4 files changed, 356 insertions(+), 32 deletions(-) create mode 100644 Tests/AsyncAlgorithmsTests/Support/MarbleDiagram.swift diff --git a/Tests/AsyncAlgorithmsTests/Support/ManualClock.swift b/Tests/AsyncAlgorithmsTests/Support/ManualClock.swift index b498d06..369d3d4 100644 --- a/Tests/AsyncAlgorithmsTests/Support/ManualClock.swift +++ b/Tests/AsyncAlgorithmsTests/Support/ManualClock.swift @@ -53,9 +53,9 @@ public struct ManualClock: Clock { public struct Instant: InstantProtocol { public typealias Duration = Step - fileprivate let rawValue: Int + internal let rawValue: Int - fileprivate init(_ rawValue: Int) { + internal init(_ rawValue: Int) { self.rawValue = rawValue } diff --git a/Tests/AsyncAlgorithmsTests/Support/MarbleDiagram.swift b/Tests/AsyncAlgorithmsTests/Support/MarbleDiagram.swift new file mode 100644 index 0000000..edb0f35 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/Support/MarbleDiagram.swift @@ -0,0 +1,321 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import AsyncAlgorithms + +public protocol MarbleDiagramTest: Sendable { + var inputs: [String] { get } + var output: String { get } + + func test(_ validator: Validator, onFinish: @Sendable @escaping () -> Void) +} + +extension XCTestCase { + @resultBuilder + public struct MarbleDiagram : Sendable { + fileprivate struct Test: MarbleDiagramTest, @unchecked Sendable where Operation.Element == String { + let inputs: [String] + let sequence: Operation + let output: String + + func test(_ validator: Validator, onFinish: @Sendable @escaping () -> Void) { + validator.test(sequence) { _ in + onFinish() + } + } + } + + fileprivate enum Event { + case step + case failure + case finish + case value(String) + } + + public struct Input: AsyncSequence, Sendable { + public typealias Element = String + enum Emission { + case value(Element) + case failure(Error) + case finish + + var result: Result { + switch self { + case .value(let value): return .success(value) + case .failure(let failure): return .failure(failure) + case .finish: return .success(nil) + } + } + } + + fileprivate struct State { + var emissions = [(ManualClock.Instant, Emission)]() + var continuations = [ManualClock.Instant: (Emission, UnsafeContinuation)]() + } + + fileprivate let state = ManagedCriticalState(State()) + fileprivate let clock: ManualClock + + public struct Iterator: AsyncIteratorProtocol { + fileprivate let state: ManagedCriticalState + fileprivate let clock: ManualClock + + public mutating func next() async throws -> Element? { + let next = state.withCriticalRegion { state -> (ManualClock.Instant, Emission)? in + guard state.emissions.count > 0 else { + return nil + } + return state.emissions.removeFirst() + } + guard let next = next else { + return nil + } + return try await withUnsafeThrowingContinuation { continuation in + state.withCriticalRegion { state in + state.continuations[next.0] = (next.1, continuation) + } + } + } + } + + public func makeAsyncIterator() -> Iterator { + Iterator(state: state, clock: clock) + } + + fileprivate static func parse(_ dsl: String) -> [(ManualClock.Instant, Emission)] { + var emissions = [(ManualClock.Instant, Emission)]() + var when = ManualClock.Instant(0) + var group: String? + for ch in dsl { + switch ch { + case "-": + if group == nil { + when += .steps(1) + } else { + group?.append(ch) + } + case "^": + if group == nil { + when += .steps(1) + emissions.append((when, .failure(Failure()))) + } else { + group?.append(ch) + } + case "|": + if group == nil { + when += .steps(1) + emissions.append((when, .finish)) + } else { + group?.append(ch) + } + case "'": + if let value = group { + group = nil + when += .steps(1) + emissions.append((when, .value(value))) + } else { + group = "" + } + case " ": + group?.append(ch) + continue + default: + if group == nil { + when += .steps(1) + emissions.append((when, .value(String(ch)))) + } else { + group?.append(ch) + } + } + } + return emissions + } + + func parse(_ dsl: String) { + let emissions = Input.parse(dsl) + state.withCriticalRegion { state in + state.emissions = emissions + } + } + } + + public struct Clock { + fileprivate let manualClock: ManualClock + + fileprivate init(_ manualClock: ManualClock) { + self.manualClock = manualClock + } + } + + public static func buildBlock(_ input: String, _ sequence: Operation, _ output: String) -> some MarbleDiagramTest where Operation.Element == String { + Test(inputs: [input], sequence: sequence, output: output) + } + + public static func buildBlock(_ input1: String, _ input2: String, _ sequence: Operation, _ output: String) -> some MarbleDiagramTest where Operation.Element == String { + Test(inputs: [input1, input2], sequence: sequence, output: output) + } + + public static func buildBlock(_ input1: String, _ input2: String, _ input3: String, _ sequence: Operation, _ output: String) -> some MarbleDiagramTest where Operation.Element == String { + Test(inputs: [input1, input2, input3], sequence: sequence, output: output) + } + + public struct InputList: RandomAccessCollection, Sendable { + fileprivate let state = ManagedCriticalState([Input]()) + fileprivate let clock: ManualClock + + public var startIndex: Int { return 0 } + public var endIndex: Int { + state.withCriticalRegion { $0.count } + } + + public subscript(position: Int) -> XCTestCase.MarbleDiagram.Input { + get { + return state.withCriticalRegion { state in + if position >= state.count { + for _ in state.count...position { + state.append(Input(clock: clock)) + } + } + return state[position] + } + } + } + } + + fileprivate let manualClock: ManualClock + public var inputs: InputList + + public var clock: Clock { + Clock(manualClock) + } + + fileprivate init(clock: ManualClock) { + self.manualClock = clock + inputs = InputList(clock: clock) + } + } + + public func marbleDiagram(@MarbleDiagram _ build: (inout MarbleDiagram) -> Test, file: StaticString = #file, line: UInt = #line) { + let finished = expectation(description: "finished") + let clock = ManualClock() + var diagram = MarbleDiagram(clock: clock) + let test = build(&diagram) + for (index, input) in diagram.inputs.enumerated() { + input.parse(test.inputs[index]) + } + var expected = Dictionary(uniqueKeysWithValues: MarbleDiagram.Input.parse(test.output).map { ($0, $1.result) }) + let actual = ManagedCriticalState([ManualClock.Instant:Result]()) + let gate = Gate() + let expectation = Gate() + let validator = Validator { event in + actual.withCriticalRegion { actual in + actual[clock.now] = event + } + await gate.enter() + expectation.open() + } + test.test(validator) { + finished.fulfill() + } + + let task = Task { [expected, diagram] in + while !Task.isCancelled { + clock.advance() + for input in diagram.inputs { + let resumption = input.state.withCriticalRegion { state in + return state.continuations.removeValue(forKey: clock.now) + } + if let resumption = resumption { + resumption.1.resume(with: resumption.0.result) + } + } + gate.open() + if expected[clock.now] != nil { + await expectation.enter() + } + } + } + wait(for: [finished], timeout: executionTimeAllowance) + task.cancel() + let collected = actual.withCriticalRegion { zip($0.keys, $0.values) } + for (instant, result) in collected { + if let expectedResult = expected.removeValue(forKey: instant) { + switch (result, expectedResult) { + case (.success(let actual), .success(let expected)): + switch (actual, expected) { + case (.some(let actual), .some(let expected)): + if actual != expected { + XCTFail("expected \(expected) at time index \(instant.rawValue) but got \(actual)", file: file, line: line) + } + case (.none, .some(let expected)): + XCTFail("expected \(expected) at time index \(instant.rawValue) but got end of iteration", file: file, line: line) + case (.some(let actual), .none): + XCTFail("expected end of iteration at time index \(instant.rawValue) but got \(actual)", file: file, line: line) + case (.none, .none): + break + } + case (.failure(let error), .success(let expected)): + if let expected = expected { + XCTFail("expected \(expected) at time index \(instant.rawValue) but got failure \(error)", file: file, line: line) + } else { + XCTFail("expected end of iteration at time index \(instant.rawValue) but got failure \(error)", file: file, line: line) + } + case (.success(let actual), .failure): + if let actual = actual { + XCTFail("expected failure at time index \(instant.rawValue) but got \(actual)", file: file, line: line) + } else { + XCTFail("expected failure at time index \(instant.rawValue) but got end of iteration", file: file, line: line) + } + case (.failure, .failure): + break + } + } else { + switch result { + case .success(let value): + if let value = value { + XCTFail("unexpected value \"\(value)\" at time index \(instant.rawValue)", file: file, line: line) + } else { + XCTFail("unexpected end of iteration at time index \(instant.rawValue)", file: file, line: line) + } + case .failure: + XCTFail("unexpected failure at time index \(instant.rawValue)", file: file, line: line) + } + } + } + for (instant, result) in expected { + switch result { + case .success(let value): + if let value = value { + XCTFail("missing expected value \"\(value)\" at time index \(instant.rawValue)", file: file, line: line) + } else { + XCTFail("missing end of iteration at time index \(instant.rawValue)", file: file, line: line) + } + case .failure: + XCTFail("missing failure at time index \(instant.rawValue)", file: file, line: line) + } + } + } +} + +extension XCTestCase.MarbleDiagram.Clock: Clock { + public var now: ManualClock.Instant { + manualClock.now + } + + public var minimumResolution: ManualClock.Step { + manualClock.minimumResolution + } + + public func sleep(until deadline: ManualClock.Instant, tolerance: ManualClock.Step? = nil) async throws { + try await manualClock.sleep(until: deadline, tolerance: tolerance) + } +} diff --git a/Tests/AsyncAlgorithmsTests/Support/Validator.swift b/Tests/AsyncAlgorithmsTests/Support/Validator.swift index eb5bc13..56d6fda 100644 --- a/Tests/AsyncAlgorithmsTests/Support/Validator.swift +++ b/Tests/AsyncAlgorithmsTests/Support/Validator.swift @@ -30,8 +30,9 @@ public struct Validator: Sendable { private let state = ManagedCriticalState(State()) - private func ready() { + private func ready(_ apply: (inout State) -> Void) { state.withCriticalRegion { state -> UnsafeContinuation? in + apply(&state) switch state.ready { case .idle: state.ready = .ready @@ -45,7 +46,7 @@ public struct Validator: Sendable { }?.resume() } - private func step() async { + internal func step() async { await withUnsafeContinuation { (continuation: UnsafeContinuation) in state.withCriticalRegion { state -> UnsafeContinuation? in switch state.ready { @@ -61,44 +62,38 @@ public struct Validator: Sendable { }?.resume() } } + + let onEvent: (@Sendable (Result) async -> Void)? + + init(onEvent: @Sendable @escaping (Result) async -> Void) { + + self.onEvent = onEvent + } + + public init() { + self.onEvent = nil + } public func test(_ sequence: S, onFinish: @Sendable @escaping (inout S.AsyncIterator) async -> Void) where S.Element == Element { let envelope = Envelope(contents: sequence) Task { var iterator = envelope.contents.makeAsyncIterator() - ready() + ready { _ in } do { while let item = try await iterator.next() { - state.withCriticalRegion { state -> UnsafeContinuation? in + await onEvent?(.success(item)) + ready { state in state.collected.append(item) - switch state.ready { - case .idle: - state.ready = .ready - return nil - case .pending(let continuation): - state.ready = .idle - return continuation - case .ready: - return nil - } - }?.resume() - } - } catch { - state.withCriticalRegion { state -> UnsafeContinuation? in - state.failure = error - switch state.ready { - case .idle: - state.ready = .ready - return nil - case .pending(let continuation): - state.ready = .idle - return continuation - case .ready: - return nil } - }?.resume() + } + await onEvent?(.success(nil)) + } catch { + await onEvent?(.failure(error)) + ready { state in + state.failure = error + } } - ready() + ready { _ in } await onFinish(&iterator) } } diff --git a/Tests/AsyncAlgorithmsTests/TestValidator.swift b/Tests/AsyncAlgorithmsTests/TestValidator.swift index 9c5ef9c..2237ec6 100644 --- a/Tests/AsyncAlgorithmsTests/TestValidator.swift +++ b/Tests/AsyncAlgorithmsTests/TestValidator.swift @@ -135,4 +135,12 @@ final class TestValidator: XCTestCase { value = validator.current XCTAssertEqual(value, [2, 3, 4]) } + + func test_diagram() { + marbleDiagram { + "a-b-c|" + $0.inputs[0].map { $0 } + "a-b-c|" + } + } }