Skip to content

Commit

Permalink
update peer test
Browse files Browse the repository at this point in the history
  • Loading branch information
MacOMNI committed Oct 24, 2024
1 parent 0f251f2 commit 798da5c
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 93 deletions.
76 changes: 0 additions & 76 deletions Networking/Sources/Networking/MockPeerEventHandler.swift

This file was deleted.

73 changes: 73 additions & 0 deletions Networking/Tests/NetworkingTests/MockPeerEventTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,79 @@ import Utils
@testable import Networking

final class MockPeerEventTests {
final class MockPeerEventHandler: QuicEventHandler {
enum EventType {
case newConnection(listener: QuicListener, connection: QuicConnection, info: ConnectionInfo)
case shouldOpen(connection: QuicConnection, certificate: Data?)
case connected(connection: QuicConnection)
case shutdownInitiated(connection: QuicConnection, reason: ConnectionCloseReason)
case streamStarted(connection: QuicConnection, stream: QuicStream)
case dataReceived(stream: QuicStream, data: Data)
case closed(stream: QuicStream, status: QuicStatus, code: QuicErrorCode)
}

let events: ThreadSafeContainer<[EventType]> = .init([])

init() {}

func newConnection(
_ listener: QuicListener, connection: QuicConnection, info: ConnectionInfo
) -> QuicStatus {
events.write { events in
events.append(.newConnection(listener: listener, connection: connection, info: info))
}

return .code(.success)
}

func shouldOpen(_: QuicConnection, certificate: Data?) -> QuicStatus {
guard let certificate else {
return .code(.requiredCert)
}
do {
let (publicKey, alternativeName) = try parseCertificate(data: certificate, type: .x509)
if alternativeName != generateSubjectAlternativeName(pubkey: publicKey) {
return .code(.badCert)
}
} catch {
return .code(.badCert)
}
return .code(.success)
}

func connected(_ connection: QuicConnection) {
events.write { events in
events.append(.connected(connection: connection))
}
}

func shutdownInitiated(_ connection: QuicConnection, reason: ConnectionCloseReason) {
print("shutdownInitiated \(connection.id) with reason \(reason)")
events.write { events in
events.append(.shutdownInitiated(connection: connection, reason: reason))
}
}

func streamStarted(_ connect: QuicConnection, stream: QuicStream) {
events.write { events in
events.append(.streamStarted(connection: connect, stream: stream))
}
}

func dataReceived(_ stream: QuicStream, data: Data) {
events.write { events in
events.append(.dataReceived(stream: stream, data: data))
}
}

func closed(_ stream: QuicStream, status: QuicStatus, code: QuicErrorCode) {
print("closed stream \(stream.id) with status \(status) and code \(code)")
events.write { events in
events.append(.closed(stream: stream, status: status, code: code))
}
}
}

let registration: QuicRegistration
let certData: Data
let badCertData: Data
Expand Down
55 changes: 38 additions & 17 deletions Networking/Tests/NetworkingTests/PeerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,20 +88,38 @@ struct PeerTests {

// deal with data
func handle(connection _: any ConnectionInfoProtocol, request: Request) async throws -> Data {
request.data
let data = request.data

guard data.count >= 4 else {
throw NSError(
domain: "ExtractError", code: 1,
userInfo: [NSLocalizedDescriptionKey: "Data too short to contain length"]
)
}
let lengthData = data.prefix(4)
let length = UInt32(
littleEndian: lengthData.withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) }
)
let actualData = data.dropFirst(4).prefix(Int(length))

return actualData
}
}

struct MockPresentStreamHandler: PresistentStreamHandler {
func streamOpened(
connection _: any Networking.ConnectionInfoProtocol,
stream _: any Networking.StreamProtocol, kind _: PeerTests.UniquePresistentStreamKind
stream _: any Networking.StreamProtocol<
PeerTests.MockRequest<PeerTests.UniquePresistentStreamKind>
>, kind _: PeerTests.UniquePresistentStreamKind

Check failure on line 114 in Networking/Tests/NetworkingTests/PeerTests.swift

View workflow job for this annotation

GitHub Actions / Swift Lint

Vertical Parameter Alignment (vertical_parameter_alignment)

Function parameters should be aligned vertically if they're in multiple lines in a declaration
) async throws {}

func handle(
connection _: any Networking.ConnectionInfoProtocol,
message _: PeerTests.MockRequest<PeerTests.UniquePresistentStreamKind>
) async throws {}
message: PeerTests.MockRequest<PeerTests.UniquePresistentStreamKind>
) async throws {
print("Present handle received: \(String(decoding: message.data, as: UTF8.self))")

Check failure on line 121 in Networking/Tests/NetworkingTests/PeerTests.swift

View workflow job for this annotation

GitHub Actions / Swift Lint

Optional Data -> String Conversion (optional_data_string_conversion)

Prefer failable `String(data:encoding:)` initializer when converting `Data` to `String`
}

typealias StreamKind = UniquePresistentStreamKind
typealias Request = MockRequest<UniquePresistentStreamKind>
Expand All @@ -118,10 +136,10 @@ struct PeerTests {
}

@Test
func peerPresentInit() async throws {
func peerBroadcast() async throws {
let peer1 = try Peer(
options: PeerOptions<MockStreamHandler>(
mode: .validator,
role: .validator,
listenAddress: NetAddr(ipAddress: "127.0.0.1", port: 8081)!,
genesisHeader: Data32(),
secretKey: Ed25519.SecretKey(from: Data32()),
Expand All @@ -133,7 +151,7 @@ struct PeerTests {
)
let peer2 = try Peer(
options: PeerOptions<MockStreamHandler>(
mode: .validator,
role: .validator,
listenAddress: NetAddr(ipAddress: "127.0.0.1", port: 8082)!,
genesisHeader: Data32(),
secretKey: Ed25519.SecretKey(from: Data32()),
Expand All @@ -145,10 +163,10 @@ struct PeerTests {
)
try? await Task.sleep(for: .milliseconds(100))
_ = try peer1.connect(
to: NetAddr(ipAddress: "127.0.0.1", port: 8082)!, mode: .validator
to: NetAddr(ipAddress: "127.0.0.1", port: 8082)!, role: .validator
)
_ = try peer2.connect(
to: NetAddr(ipAddress: "127.0.0.1", port: 8081)!, mode: .validator
to: NetAddr(ipAddress: "127.0.0.1", port: 8081)!, role: .validator
)
try? await Task.sleep(for: .milliseconds(100))
peer1.broadcast(
Expand All @@ -162,10 +180,10 @@ struct PeerTests {
}

@Test
func peerEphemeralInit() async throws {
func peerRequest() async throws {
let peer1 = try Peer(
options: PeerOptions<MockStreamHandler>(
mode: .validator,
role: .validator,
listenAddress: NetAddr(ipAddress: "127.0.0.1", port: 8083)!,
genesisHeader: Data32(),
secretKey: Ed25519.SecretKey(from: Data32()),
Expand All @@ -177,7 +195,7 @@ struct PeerTests {
)
let peer2 = try Peer(
options: PeerOptions<MockStreamHandler>(
mode: .validator,
role: .validator,
listenAddress: NetAddr(ipAddress: "127.0.0.1", port: 8084)!,
genesisHeader: Data32(),
secretKey: Ed25519.SecretKey(from: Data32()),
Expand All @@ -188,22 +206,25 @@ struct PeerTests {
)
)
try? await Task.sleep(for: .milliseconds(100))

let connection1 = try peer1.connect(
to: NetAddr(ipAddress: "127.0.0.1", port: 8084)!, mode: .validator
to: NetAddr(ipAddress: "127.0.0.1", port: 8084)!, role: .validator
)
try? await Task.sleep(for: .milliseconds(100))

let data1 = try await connection1.request(
MockRequest(kind: .typeA, data: Data("hello world".utf8))
)
#expect(data1 == Data("hello world".utf8))
#expect(data1.suffix(from: 4) == Data("hello world".utf8))

let connection2 = try peer2.connect(
to: NetAddr(ipAddress: "127.0.0.1", port: 8083)!, mode: .validator
to: NetAddr(ipAddress: "127.0.0.1", port: 8083)!, role: .validator
)
try? await Task.sleep(for: .milliseconds(100))

let data2 = try await connection2.request(
MockRequest(kind: .typeB, data: Data("I am jam".utf8))
)
#expect(data2 == Data("I am jam".utf8))
try? await Task.sleep(for: .milliseconds(100))
#expect(data2.suffix(from: 4) == Data("I am jam".utf8))
}
}

0 comments on commit 798da5c

Please sign in to comment.