|
| 1 | +import AsyncTraverse |
| 2 | +import SwiftProtobuf |
| 3 | +import XCTest |
| 4 | + |
| 5 | +final class AsyncTraverseTests: XCTestCase { |
| 6 | + func testAsyncTraverse() async throws { |
| 7 | + var message = AsyncTraverseMessage.with { |
| 8 | + $0.data = .init([UInt8(0)]) |
| 9 | + $0.nested = .with { |
| 10 | + $0.data = .init([UInt8(1)]) |
| 11 | + $0.nestedNested = .with { |
| 12 | + $0.data = .init([UInt8(2)]) |
| 13 | + } |
| 14 | + } |
| 15 | + $0.repeatedData = [.init([UInt8(3)]), .init([UInt8(4)])] |
| 16 | + $0.repeatedNested = [ |
| 17 | + .with { |
| 18 | + $0.data = .init([UInt8(5)]) |
| 19 | + $0.nestedNested = .with { |
| 20 | + $0.data = .init([UInt8(6)]) |
| 21 | + } |
| 22 | + } |
| 23 | + ] |
| 24 | + } |
| 25 | + var visitor = MyVisitor() |
| 26 | + try await message.traverse(visitor: &visitor) |
| 27 | + XCTAssertEqual(message.data, .init([UInt8(1)])) |
| 28 | + XCTAssertEqual(message.nested.data, .init([UInt8(2)])) |
| 29 | + XCTAssertEqual(message.nested.nestedNested.data, .init([UInt8(3)])) |
| 30 | + XCTAssertEqual(message.repeatedData, [.init([UInt8(4)]), .init([UInt8(5)])]) |
| 31 | + XCTAssertEqual(message.repeatedNested[0].data, .init([UInt8(6)])) |
| 32 | + XCTAssertEqual(message.repeatedNested[0].nestedNested.data, .init([UInt8(7)])) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +struct MyVisitor: AsyncVisitor { |
| 37 | + mutating func visitSingularMessageField(value: inout some Message, fieldNumber: Int) async throws { |
| 38 | + try await value.traverse(visitor: &self) |
| 39 | + } |
| 40 | + |
| 41 | + mutating func visitRepeatedMessageField<M>(value: inout [M], fieldNumber: Int) async throws |
| 42 | + where M: SwiftProtobuf.Message { |
| 43 | + for index in value.indices { |
| 44 | + try await value[index].traverse(visitor: &self) |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + mutating func visitSingularBytesField(value: inout Data, fieldNumber: Int) async throws { |
| 49 | + value = Data([value.first! + UInt8(1)]) |
| 50 | + } |
| 51 | + mutating func visitRepeatedBytesField(value: inout [Data], fieldNumber: Int) async throws { |
| 52 | + value = value.map { Data([$0.first! + UInt8(1)]) } |
| 53 | + } |
| 54 | +} |
0 commit comments