StructuredSwift+ServerTests.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * Copyright 2024, 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 Testing
  17. @testable import GRPCCodeGen
  18. extension StructuredSwiftTests {
  19. @Suite("Server")
  20. struct Server {
  21. @Test(
  22. "func <Method>(request:context:) async throws -> ...",
  23. arguments: AccessModifier.allCases,
  24. RPCKind.allCases
  25. )
  26. @available(gRPCSwift 2.0, *)
  27. func serverMethodSignature(access: AccessModifier, kind: RPCKind) {
  28. let decl: FunctionSignatureDescription = .serverMethod(
  29. accessLevel: access,
  30. name: "foo",
  31. input: "Input",
  32. output: "Output",
  33. streamingInput: kind.streamsInput,
  34. streamingOutput: kind.streamsOutput
  35. )
  36. let expected: String
  37. switch kind {
  38. case .unary:
  39. expected = """
  40. \(access) func foo(
  41. request: GRPCCore.ServerRequest<Input>,
  42. context: GRPCCore.ServerContext
  43. ) async throws -> GRPCCore.ServerResponse<Output>
  44. """
  45. case .clientStreaming:
  46. expected = """
  47. \(access) func foo(
  48. request: GRPCCore.StreamingServerRequest<Input>,
  49. context: GRPCCore.ServerContext
  50. ) async throws -> GRPCCore.ServerResponse<Output>
  51. """
  52. case .serverStreaming:
  53. expected = """
  54. \(access) func foo(
  55. request: GRPCCore.ServerRequest<Input>,
  56. context: GRPCCore.ServerContext
  57. ) async throws -> GRPCCore.StreamingServerResponse<Output>
  58. """
  59. case .bidirectionalStreaming:
  60. expected = """
  61. \(access) func foo(
  62. request: GRPCCore.StreamingServerRequest<Input>,
  63. context: GRPCCore.ServerContext
  64. ) async throws -> GRPCCore.StreamingServerResponse<Output>
  65. """
  66. }
  67. #expect(render(.function(signature: decl)) == expected)
  68. }
  69. @Test("protocol StreamingServiceProtocol { ... }", arguments: AccessModifier.allCases)
  70. @available(gRPCSwift 2.0, *)
  71. func serverStreamingServiceProtocol(access: AccessModifier) {
  72. let decl: ProtocolDescription = .streamingService(
  73. accessLevel: access,
  74. name: "FooService",
  75. methods: [
  76. .init(
  77. documentation: "/// Some docs",
  78. name: MethodName(identifyingName: "Foo", typeName: "Foo", functionName: "foo"),
  79. isInputStreaming: false,
  80. isOutputStreaming: false,
  81. inputType: "FooInput",
  82. outputType: "FooOutput"
  83. )
  84. ]
  85. )
  86. let expected = """
  87. \(access) protocol FooService: GRPCCore.RegistrableRPCService {
  88. /// Handle the "Foo" method.
  89. ///
  90. /// > Source IDL Documentation:
  91. /// >
  92. /// > Some docs
  93. ///
  94. /// - Parameters:
  95. /// - request: A streaming request of `FooInput` messages.
  96. /// - context: Context providing information about the RPC.
  97. /// - Throws: Any error which occurred during the processing of the request. Thrown errors
  98. /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted
  99. /// to an internal error.
  100. /// - Returns: A streaming response of `FooOutput` messages.
  101. func foo(
  102. request: GRPCCore.StreamingServerRequest<FooInput>,
  103. context: GRPCCore.ServerContext
  104. ) async throws -> GRPCCore.StreamingServerResponse<FooOutput>
  105. }
  106. """
  107. #expect(render(.protocol(decl)) == expected)
  108. }
  109. @Test("protocol ServiceProtocol { ... }", arguments: AccessModifier.allCases)
  110. @available(gRPCSwift 2.0, *)
  111. func serverServiceProtocol(access: AccessModifier) {
  112. let decl: ProtocolDescription = .service(
  113. accessLevel: access,
  114. name: "FooService",
  115. streamingProtocol: "FooService_StreamingServiceProtocol",
  116. methods: [
  117. .init(
  118. documentation: "/// Some docs",
  119. name: MethodName(identifyingName: "Foo", typeName: "Foo", functionName: "foo"),
  120. isInputStreaming: false,
  121. isOutputStreaming: false,
  122. inputType: "FooInput",
  123. outputType: "FooOutput"
  124. )
  125. ]
  126. )
  127. let expected = """
  128. \(access) protocol FooService: FooService_StreamingServiceProtocol {
  129. /// Handle the "Foo" method.
  130. ///
  131. /// > Source IDL Documentation:
  132. /// >
  133. /// > Some docs
  134. ///
  135. /// - Parameters:
  136. /// - request: A request containing a single `FooInput` message.
  137. /// - context: Context providing information about the RPC.
  138. /// - Throws: Any error which occurred during the processing of the request. Thrown errors
  139. /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted
  140. /// to an internal error.
  141. /// - Returns: A response containing a single `FooOutput` message.
  142. func foo(
  143. request: GRPCCore.ServerRequest<FooInput>,
  144. context: GRPCCore.ServerContext
  145. ) async throws -> GRPCCore.ServerResponse<FooOutput>
  146. }
  147. """
  148. #expect(render(.protocol(decl)) == expected)
  149. }
  150. @Test("{ router, context in try await self.<Method>(...) }")
  151. @available(gRPCSwift 2.0, *)
  152. func routerHandlerInvokingRPC() {
  153. let expression: ClosureInvocationDescription = .routerHandlerInvokingRPC(method: "foo")
  154. let expected = """
  155. { request, context in
  156. try await self.foo(
  157. request: request,
  158. context: context
  159. )
  160. }
  161. """
  162. #expect(render(.closureInvocation(expression)) == expected)
  163. }
  164. @Test("router.registerHandler(...) { ... }")
  165. @available(gRPCSwift 2.0, *)
  166. func registerMethodsWithRouter() {
  167. let expression: FunctionCallDescription = .registerWithRouter(
  168. serviceNamespace: "FooService",
  169. methodNamespace: "Bar",
  170. methodName: "bar",
  171. inputDeserializer: "Deserialize<BarInput>()",
  172. outputSerializer: "Serialize<BarOutput>()"
  173. )
  174. let expected = """
  175. router.registerHandler(
  176. forMethod: FooService.Method.Bar.descriptor,
  177. deserializer: Deserialize<BarInput>(),
  178. serializer: Serialize<BarOutput>(),
  179. handler: { request, context in
  180. try await self.bar(
  181. request: request,
  182. context: context
  183. )
  184. }
  185. )
  186. """
  187. #expect(render(.functionCall(expression)) == expected)
  188. }
  189. @Test("func registerMethods(router:)", arguments: AccessModifier.allCases)
  190. @available(gRPCSwift 2.0, *)
  191. func registerMethods(access: AccessModifier) {
  192. let expression: FunctionDescription = .registerMethods(
  193. accessLevel: access,
  194. serviceNamespace: "FooService",
  195. methods: [
  196. .init(
  197. documentation: "",
  198. name: MethodName(identifyingName: "Bar", typeName: "Bar", functionName: "bar"),
  199. isInputStreaming: false,
  200. isOutputStreaming: false,
  201. inputType: "BarInput",
  202. outputType: "BarOutput"
  203. )
  204. ]
  205. ) { type in
  206. "Serialize<\(type)>()"
  207. } deserializer: { type in
  208. "Deserialize<\(type)>()"
  209. }
  210. let expected = """
  211. \(access) func registerMethods<Transport>(with router: inout GRPCCore.RPCRouter<Transport>) where Transport: GRPCCore.ServerTransport {
  212. router.registerHandler(
  213. forMethod: FooService.Method.Bar.descriptor,
  214. deserializer: Deserialize<BarInput>(),
  215. serializer: Serialize<BarOutput>(),
  216. handler: { request, context in
  217. try await self.bar(
  218. request: request,
  219. context: context
  220. )
  221. }
  222. )
  223. }
  224. """
  225. #expect(render(.function(expression)) == expected)
  226. }
  227. @Test(
  228. "func <Method>(request:context:) async throw { ... (convert to/from single) ... }",
  229. arguments: AccessModifier.allCases,
  230. RPCKind.allCases
  231. )
  232. @available(gRPCSwift 2.0, *)
  233. func serverStreamingMethodsCallingMethod(access: AccessModifier, kind: RPCKind) {
  234. let expression: FunctionDescription = .serverStreamingMethodsCallingMethod(
  235. accessLevel: access,
  236. name: "foo",
  237. input: "Input",
  238. output: "Output",
  239. streamingInput: kind.streamsInput,
  240. streamingOutput: kind.streamsOutput
  241. )
  242. let expected: String
  243. switch kind {
  244. case .unary:
  245. expected = """
  246. \(access) func foo(
  247. request: GRPCCore.StreamingServerRequest<Input>,
  248. context: GRPCCore.ServerContext
  249. ) async throws -> GRPCCore.StreamingServerResponse<Output> {
  250. let response = try await self.foo(
  251. request: GRPCCore.ServerRequest(stream: request),
  252. context: context
  253. )
  254. return GRPCCore.StreamingServerResponse(single: response)
  255. }
  256. """
  257. case .serverStreaming:
  258. expected = """
  259. \(access) func foo(
  260. request: GRPCCore.StreamingServerRequest<Input>,
  261. context: GRPCCore.ServerContext
  262. ) async throws -> GRPCCore.StreamingServerResponse<Output> {
  263. let response = try await self.foo(
  264. request: GRPCCore.ServerRequest(stream: request),
  265. context: context
  266. )
  267. return response
  268. }
  269. """
  270. case .clientStreaming:
  271. expected = """
  272. \(access) func foo(
  273. request: GRPCCore.StreamingServerRequest<Input>,
  274. context: GRPCCore.ServerContext
  275. ) async throws -> GRPCCore.StreamingServerResponse<Output> {
  276. let response = try await self.foo(
  277. request: request,
  278. context: context
  279. )
  280. return GRPCCore.StreamingServerResponse(single: response)
  281. }
  282. """
  283. case .bidirectionalStreaming:
  284. expected = """
  285. \(access) func foo(
  286. request: GRPCCore.StreamingServerRequest<Input>,
  287. context: GRPCCore.ServerContext
  288. ) async throws -> GRPCCore.StreamingServerResponse<Output> {
  289. let response = try await self.foo(
  290. request: request,
  291. context: context
  292. )
  293. return response
  294. }
  295. """
  296. }
  297. #expect(render(.function(expression)) == expected)
  298. }
  299. @Test("extension FooService_ServiceProtocol { ... }", arguments: AccessModifier.allCases)
  300. @available(gRPCSwift 2.0, *)
  301. func streamingServiceProtocolDefaultImplementation(access: AccessModifier) {
  302. let decl: ExtensionDescription = .streamingServiceProtocolDefaultImplementation(
  303. accessModifier: access,
  304. on: "Foo_ServiceProtocol",
  305. methods: [
  306. .init(
  307. documentation: "",
  308. name: MethodName(identifyingName: "Foo", typeName: "Foo", functionName: "foo"),
  309. isInputStreaming: false,
  310. isOutputStreaming: false,
  311. inputType: "FooInput",
  312. outputType: "FooOutput"
  313. ),
  314. // Will be ignored as a bidirectional streaming method.
  315. .init(
  316. documentation: "",
  317. name: MethodName(identifyingName: "Bar", typeName: "Bar", functionName: "bar"),
  318. isInputStreaming: true,
  319. isOutputStreaming: true,
  320. inputType: "BarInput",
  321. outputType: "BarOutput"
  322. ),
  323. ]
  324. )
  325. let expected = """
  326. extension Foo_ServiceProtocol {
  327. \(access) func foo(
  328. request: GRPCCore.StreamingServerRequest<FooInput>,
  329. context: GRPCCore.ServerContext
  330. ) async throws -> GRPCCore.StreamingServerResponse<FooOutput> {
  331. let response = try await self.foo(
  332. request: GRPCCore.ServerRequest(stream: request),
  333. context: context
  334. )
  335. return GRPCCore.StreamingServerResponse(single: response)
  336. }
  337. }
  338. """
  339. #expect(render(.extension(decl)) == expected)
  340. }
  341. @Test(
  342. "func <Method>(request:response:context:) (simple)",
  343. arguments: AccessModifier.allCases,
  344. RPCKind.allCases
  345. )
  346. @available(gRPCSwift 2.0, *)
  347. func simpleServerMethod(access: AccessModifier, kind: RPCKind) {
  348. let decl: FunctionSignatureDescription = .simpleServerMethod(
  349. accessLevel: access,
  350. name: "foo",
  351. input: "FooInput",
  352. output: "FooOutput",
  353. streamingInput: kind.streamsInput,
  354. streamingOutput: kind.streamsOutput
  355. )
  356. let expected: String
  357. switch kind {
  358. case .unary:
  359. expected = """
  360. \(access) func foo(
  361. request: FooInput,
  362. context: GRPCCore.ServerContext
  363. ) async throws -> FooOutput
  364. """
  365. case .clientStreaming:
  366. expected = """
  367. \(access) func foo(
  368. request: GRPCCore.RPCAsyncSequence<FooInput, any Swift.Error>,
  369. context: GRPCCore.ServerContext
  370. ) async throws -> FooOutput
  371. """
  372. case .serverStreaming:
  373. expected = """
  374. \(access) func foo(
  375. request: FooInput,
  376. response: GRPCCore.RPCWriter<FooOutput>,
  377. context: GRPCCore.ServerContext
  378. ) async throws
  379. """
  380. case .bidirectionalStreaming:
  381. expected = """
  382. \(access) func foo(
  383. request: GRPCCore.RPCAsyncSequence<FooInput, any Swift.Error>,
  384. response: GRPCCore.RPCWriter<FooOutput>,
  385. context: GRPCCore.ServerContext
  386. ) async throws
  387. """
  388. }
  389. #expect(render(.function(signature: decl)) == expected)
  390. }
  391. @Test("protocol SimpleServiceProtocol { ... }", arguments: AccessModifier.allCases)
  392. @available(gRPCSwift 2.0, *)
  393. func simpleServiceProtocol(access: AccessModifier) {
  394. let decl: ProtocolDescription = .simpleServiceProtocol(
  395. accessModifier: access,
  396. name: "SimpleServiceProtocol",
  397. serviceProtocol: "ServiceProtocol",
  398. methods: [
  399. .init(
  400. documentation: "",
  401. name: MethodName(identifyingName: "Foo", typeName: "Foo", functionName: "foo"),
  402. isInputStreaming: false,
  403. isOutputStreaming: false,
  404. inputType: "Input",
  405. outputType: "Output"
  406. )
  407. ]
  408. )
  409. let expected = """
  410. \(access) protocol SimpleServiceProtocol: ServiceProtocol {
  411. /// Handle the "Foo" method.
  412. ///
  413. /// - Parameters:
  414. /// - request: A `Input` message.
  415. /// - context: Context providing information about the RPC.
  416. /// - Throws: Any error which occurred during the processing of the request. Thrown errors
  417. /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted
  418. /// to an internal error.
  419. /// - Returns: A `Output` to respond with.
  420. func foo(
  421. request: Input,
  422. context: GRPCCore.ServerContext
  423. ) async throws -> Output
  424. }
  425. """
  426. #expect(render(.protocol(decl)) == expected)
  427. }
  428. }
  429. }