RPCRouterTests.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright 2023, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import GRPCCore
  17. import XCTest
  18. @available(gRPCSwift 2.0, *)
  19. final class RPCRouterTests: XCTestCase {
  20. func testEmptyRouter() async throws {
  21. var router = RPCRouter<NoServerTransport>()
  22. XCTAssertEqual(router.count, 0)
  23. XCTAssertEqual(router.methods, [])
  24. XCTAssertFalse(
  25. router.hasHandler(forMethod: MethodDescriptor(fullyQualifiedService: "foo", method: "bar"))
  26. )
  27. XCTAssertFalse(
  28. router.removeHandler(forMethod: MethodDescriptor(fullyQualifiedService: "foo", method: "bar"))
  29. )
  30. }
  31. func testRegisterMethod() async throws {
  32. var router = RPCRouter<NoServerTransport>()
  33. let method = MethodDescriptor(fullyQualifiedService: "foo", method: "bar")
  34. router.registerHandler(
  35. forMethod: method,
  36. deserializer: IdentityDeserializer(),
  37. serializer: IdentitySerializer()
  38. ) { _, _ in
  39. throw RPCError(code: .failedPrecondition, message: "Shouldn't be called")
  40. }
  41. XCTAssertEqual(router.count, 1)
  42. XCTAssertEqual(router.methods, [method])
  43. XCTAssertTrue(router.hasHandler(forMethod: method))
  44. }
  45. func testRemoveMethod() async throws {
  46. var router = RPCRouter<NoServerTransport>()
  47. let method = MethodDescriptor(fullyQualifiedService: "foo", method: "bar")
  48. router.registerHandler(
  49. forMethod: method,
  50. deserializer: IdentityDeserializer(),
  51. serializer: IdentitySerializer()
  52. ) { _, _ in
  53. throw RPCError(code: .failedPrecondition, message: "Shouldn't be called")
  54. }
  55. XCTAssertTrue(router.removeHandler(forMethod: method))
  56. XCTAssertFalse(router.hasHandler(forMethod: method))
  57. XCTAssertEqual(router.count, 0)
  58. XCTAssertEqual(router.methods, [])
  59. }
  60. }
  61. @available(gRPCSwift 2.0, *)
  62. struct NoServerTransport: ServerTransport {
  63. typealias Bytes = [UInt8]
  64. func listen(
  65. streamHandler: @escaping @Sendable (
  66. GRPCCore.RPCStream<Inbound, Outbound>,
  67. GRPCCore.ServerContext
  68. ) async -> Void
  69. ) async throws {
  70. }
  71. func beginGracefulShutdown() {
  72. }
  73. }