main.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import SwiftGRPCNIO
  18. import NIO
  19. import NIOSSL
  20. import SwiftGRPCNIOInteroperabilityTests
  21. import Commander
  22. enum InteroperabilityTestError: LocalizedError {
  23. case testNotFound(String)
  24. case testFailed(Error)
  25. var errorDescription: String? {
  26. switch self {
  27. case .testNotFound(let name):
  28. return "No test named '\(name)' was found"
  29. case .testFailed(let error):
  30. return "Test failed with error: \(error)"
  31. }
  32. }
  33. }
  34. /// Runs the test instance using the given connection.
  35. ///
  36. /// Success or failure is indicated by the lack or presence of thrown errors, respectively.
  37. ///
  38. /// - Parameters:
  39. /// - instance: `InteroperabilityTest` instance to run.
  40. /// - name: the name of the test, use for logging only.
  41. /// - connection: client connection to use for running the test.
  42. /// - Throws: `InteroperabilityTestError` if the test fails.
  43. func runTest(_ instance: InteroperabilityTest, name: String, connection: GRPCClientConnection) throws {
  44. do {
  45. print("Running '\(name)' ... ", terminator: "")
  46. try instance.run(using: connection)
  47. print("PASSED")
  48. } catch {
  49. print("FAILED")
  50. throw InteroperabilityTestError.testFailed(error)
  51. }
  52. }
  53. /// Creates a new `InteroperabilityTest` instance with the given name, or throws an
  54. /// `InteroperabilityTestError` if no test matches the given name. Implemented test names can be
  55. /// found by running the `list_tests` target.
  56. func makeRunnableTest(name: String) throws -> InteroperabilityTest {
  57. guard let testCase = InteroperabilityTestCase(rawValue: name) else {
  58. throw InteroperabilityTestError.testNotFound(name)
  59. }
  60. return testCase.makeTest()
  61. }
  62. /// Runs the given block and exits with code 1 if the block throws an error.
  63. ///
  64. /// The "Commander" CLI elides thrown errors in favour of its own. This function is intended purely
  65. /// to work around this limitation by printing any errors before exiting.
  66. func exitOnThrow<T>(block: () throws -> T) -> T {
  67. do {
  68. return try block()
  69. } catch {
  70. print(error)
  71. exit(1)
  72. }
  73. }
  74. // MARK: - Optional extensions for Commander
  75. // "Commander" doesn't allow us to have no value for an `Option` and using a sentinel value to
  76. // indicate a lack of value isn't very Swift-y when we have `Optional`.
  77. extension Optional: CustomStringConvertible where Wrapped: ArgumentConvertible {
  78. public var description: String {
  79. guard let value = self else {
  80. return "None"
  81. }
  82. return "Some(\(value))"
  83. }
  84. }
  85. extension Optional: ArgumentConvertible where Wrapped: ArgumentConvertible {
  86. public init(parser: ArgumentParser) throws {
  87. if let wrapped = parser.shift() as? Wrapped {
  88. self = wrapped
  89. } else {
  90. self = .none
  91. }
  92. }
  93. }
  94. // MARK: - Command line options and "main".
  95. let serverHostOption = Option(
  96. "server_host",
  97. default: "localhost",
  98. description: "The server host to connect to.")
  99. let serverPortOption = Option(
  100. "server_port",
  101. default: 8080,
  102. description: "The server port to connect to.")
  103. let testCaseOption = Option(
  104. "test_case",
  105. default: InteroperabilityTestCase.emptyUnary.name,
  106. description: "The name of the test case to execute.")
  107. /// The spec requires a string (as opposed to having a flag) to indicate whether TLS is enabled or
  108. /// disabled.
  109. let useTLSOption = Option(
  110. "use_tls",
  111. default: "false",
  112. description: "Whether to use an encrypted or plaintext connection (true|false).") { value in
  113. let lowercased = value.lowercased()
  114. switch lowercased {
  115. case "true", "false":
  116. return lowercased
  117. default:
  118. throw ArgumentError.invalidType(value: value, type: "boolean", argument: "use_tls")
  119. }
  120. }
  121. let portOption = Option(
  122. "port",
  123. default: 8080,
  124. description: "The port to listen on.")
  125. let group = Group { group in
  126. group.command(
  127. "run_test",
  128. serverHostOption,
  129. serverPortOption,
  130. useTLSOption,
  131. testCaseOption,
  132. description: "Run a single test. See 'list_tests' for available test names."
  133. ) { host, port, useTLS, testCaseName in
  134. let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  135. defer {
  136. try? eventLoopGroup.syncShutdownGracefully()
  137. }
  138. exitOnThrow {
  139. let instance = try makeRunnableTest(name: testCaseName)
  140. let connection = try makeInteroperabilityTestClientConnection(
  141. host: host,
  142. port: port,
  143. eventLoopGroup: eventLoopGroup,
  144. useTLS: useTLS == "true").wait()
  145. try runTest(instance, name: testCaseName, connection: connection)
  146. }
  147. }
  148. group.command(
  149. "start_server",
  150. portOption,
  151. useTLSOption,
  152. description: "Starts the test server."
  153. ) { port, useTls in
  154. let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  155. defer {
  156. try? eventLoopGroup.syncShutdownGracefully()
  157. }
  158. let server = exitOnThrow {
  159. return try makeInteroperabilityTestServer(
  160. host: "localhost",
  161. port: port,
  162. eventLoopGroup: eventLoopGroup,
  163. useTLS: useTls == "true")
  164. }
  165. server.map { $0.channel.localAddress?.port }.whenSuccess {
  166. print("Server started on port \($0!)")
  167. }
  168. // We never call close; run until we get killed.
  169. try server.flatMap { $0.onClose }.wait()
  170. }
  171. group.command(
  172. "list_tests",
  173. description: "List available test case names."
  174. ) {
  175. InteroperabilityTestCase.allCases.forEach {
  176. print($0.name)
  177. }
  178. }
  179. }
  180. group.run()