main.swift 5.3 KB

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