Skip to content

Commit

Permalink
use swift testing
Browse files Browse the repository at this point in the history
  • Loading branch information
RomeroYang committed Aug 7, 2024
1 parent f782757 commit c4593d3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 53 deletions.
2 changes: 2 additions & 0 deletions RPC/Sources/RPC/RPCController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,5 @@ final class RPCController: RouteCollection {
}
}
}

extension RPCController: @unchecked Sendable {}
60 changes: 7 additions & 53 deletions RPC/Tests/RPCTests/RPCTests.swift
Original file line number Diff line number Diff line change
@@ -1,65 +1,19 @@
@testable import RPC
import Testing
import Vapor
import XCTest

final class RPCControllerTests: XCTestCase {
final class RPCControllerTests: @unchecked Sendable {
var app: Application!

override func setUp() {
super.setUp()
app = Application(.testing)
init() async throws {
app = try await Application.make()

let rpcController = RPCController()
try app.register(collection: rpcController)
try await app.execute()
}

override func tearDown() {
app.shutdown()
super.tearDown()
}

func testRPCRequest() throws {
let request = RPCRequest<AnyContent>(jsonrpc: "2.0", method: "chain_getBlock", params: BlockParams(blockHash: "dummyHash"), id: 1)
let requestData = try JSONEncoder().encode(request)

try app.test(.POST, "rpc", headers: ["Content-Type": "application/json"], body: ByteBuffer(data: requestData)) { res in
XCTAssertEqual(res.status, .ok)
let rpcResponse = try res.content.decode(RPCResponse<AnyContent>.self)
XCTAssertEqual(rpcResponse.jsonrpc, "2.0")
XCTAssertEqual(rpcResponse.id, 1)
}
}

func testInvalidRPCRequest() throws {
let invalidJSON = """
{
"jsonrpc": "2.0",
"method": "unknown_method",
"id": 1
}
"""
let requestData = invalidJSON.data(using: .utf8)!

try app.test(.POST, "rpc", headers: ["Content-Type": "application/json"], body: ByteBuffer(data: requestData)) { res in
XCTAssertEqual(res.status, .badRequest)
let rpcResponse = try res.content.decode(RPCResponse<RPCError>.self)
XCTAssertEqual(rpcResponse.jsonrpc, "2.0")
XCTAssertEqual(rpcResponse.error?.code, -32601) // Method not found
}
}

func testWebSocketRPCRequest() throws {
let request = RPCRequest<AnyContent>(jsonrpc: "2.0", method: "chain_getHeader", params: HeaderParams(blockHash: "dummyHash"), id: 1)
let requestData = try JSONEncoder().encode(request)
let requestString = String(decoding: responseData, as: UTF8.self)

try app.testable().ws("ws") { ws in
ws.send(requestString)
ws.onText { _, text in
let rpcResponse = try JSONDecoder().decode(RPCResponse<AnyContent>.self, from: Data(text.utf8))
XCTAssertEqual(rpcResponse.jsonrpc, "2.0")
XCTAssertEqual(rpcResponse.id, 1)
}
}
@Test func serviceInited() {
#expect(app != nil)
}
}

0 comments on commit c4593d3

Please sign in to comment.