FakeChannel.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. /*
  2. * Copyright 2020, 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 NIO
  17. import Logging
  18. /// A fake channel for use with generated test clients.
  19. ///
  20. /// The `FakeChannel` provides factories for calls which avoid most of the gRPC stack and don't do
  21. /// real networking. Each call relies on either a `FakeUnaryResponse` or a `FakeStreamingResponse`
  22. /// to get responses or errors. The fake response of each type should be registered with the channel
  23. /// prior to making a call via `makeFakeUnaryResponse` or `makeFakeStreamingResponse` respectively.
  24. ///
  25. /// Users will typically not be required to interact with the channel directly, instead they should
  26. /// do so via a generated test client.
  27. public class FakeChannel: GRPCChannel {
  28. /// Fake response streams keyed by their path.
  29. private var responseStreams: [String: CircularBuffer<Any>]
  30. /// A logger.
  31. public let logger: Logger
  32. public init(logger: Logger = Logger(label: "io.grpc.testing")) {
  33. self.responseStreams = [:]
  34. self.logger = logger
  35. }
  36. /// Make and store a fake unary response for the given path. Users should prefer making a response
  37. /// stream for their RPC directly via the appropriate method on their generated test client.
  38. public func makeFakeUnaryResponse<Request: GRPCPayload, Response: GRPCPayload>(
  39. path: String,
  40. requestHandler: @escaping (FakeRequestPart<Request>) -> ()
  41. ) -> FakeUnaryResponse<Request, Response> {
  42. let proxy = FakeUnaryResponse<Request, Response>(requestHandler: requestHandler)
  43. self.responseStreams[path, default: []].append(proxy)
  44. return proxy
  45. }
  46. /// Make and store a fake streaming response for the given path. Users should prefer making a
  47. /// response stream for their RPC directly via the appropriate method on their generated test
  48. /// client.
  49. public func makeFakeStreamingResponse<Request: GRPCPayload, Response: GRPCPayload>(
  50. path: String,
  51. requestHandler: @escaping (FakeRequestPart<Request>) -> ()
  52. ) -> FakeStreamingResponse<Request, Response> {
  53. let proxy = FakeStreamingResponse<Request, Response>(requestHandler: requestHandler)
  54. self.responseStreams[path, default: []].append(proxy)
  55. return proxy
  56. }
  57. // (Docs inherited from `GRPCChannel`)
  58. public func makeUnaryCall<Request: GRPCPayload, Response: GRPCPayload>(
  59. path: String,
  60. request: Request,
  61. callOptions: CallOptions
  62. ) -> UnaryCall<Request, Response> {
  63. let call = UnaryCall<Request, Response>.make(
  64. fakeResponse: self.dequeueResponseStream(forPath: path),
  65. callOptions: callOptions,
  66. logger: self.logger
  67. )
  68. call.send(self.makeRequestHead(path: path, callOptions: callOptions), request: request)
  69. return call
  70. }
  71. // (Docs inherited from `GRPCChannel`)
  72. public func makeServerStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  73. path: String,
  74. request: Request,
  75. callOptions: CallOptions,
  76. handler: @escaping (Response) -> Void
  77. ) -> ServerStreamingCall<Request, Response> {
  78. let call = ServerStreamingCall<Request, Response>.make(
  79. fakeResponse: self.dequeueResponseStream(forPath: path),
  80. callOptions: callOptions,
  81. logger: self.logger,
  82. responseHandler: handler
  83. )
  84. call.send(self.makeRequestHead(path: path, callOptions: callOptions), request: request)
  85. return call
  86. }
  87. // (Docs inherited from `GRPCChannel`)
  88. public func makeClientStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  89. path: String,
  90. callOptions: CallOptions
  91. ) -> ClientStreamingCall<Request, Response> {
  92. let call = ClientStreamingCall<Request, Response>.make(
  93. fakeResponse: self.dequeueResponseStream(forPath: path),
  94. callOptions: callOptions,
  95. logger: self.logger
  96. )
  97. call.sendHead(self.makeRequestHead(path: path, callOptions: callOptions))
  98. return call
  99. }
  100. // (Docs inherited from `GRPCChannel`)
  101. public func makeBidirectionalStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  102. path: String,
  103. callOptions: CallOptions,
  104. handler: @escaping (Response) -> Void
  105. ) -> BidirectionalStreamingCall<Request, Response> {
  106. let call = BidirectionalStreamingCall<Request, Response>.make(
  107. fakeResponse: self.dequeueResponseStream(forPath: path),
  108. callOptions: callOptions,
  109. logger: self.logger,
  110. responseHandler: handler
  111. )
  112. call.sendHead(self.makeRequestHead(path: path, callOptions: callOptions))
  113. return call
  114. }
  115. public func close() -> EventLoopFuture<Void> {
  116. // We don't have anything to close.
  117. return EmbeddedEventLoop().makeSucceededFuture(())
  118. }
  119. }
  120. extension FakeChannel {
  121. /// Dequeue a proxy for the given path and casts it to the given type, if one exists.
  122. private func dequeueResponseStream<Stream>(
  123. forPath path: String,
  124. as: Stream.Type = Stream.self
  125. ) -> Stream? {
  126. guard var streams = self.responseStreams[path], !streams.isEmpty else {
  127. return nil
  128. }
  129. // This is fine: we know we're non-empty.
  130. let first = streams.removeFirst()
  131. self.responseStreams.updateValue(streams, forKey: path)
  132. return first as? Stream
  133. }
  134. private func makeRequestHead(path: String, callOptions: CallOptions) -> _GRPCRequestHead {
  135. return _GRPCRequestHead(
  136. scheme: "http",
  137. path: path,
  138. host: "localhost",
  139. requestID: callOptions.requestIDProvider.requestID(),
  140. options: callOptions
  141. )
  142. }
  143. }