FakeChannel.swift 5.7 KB

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