GRPCTestCase.swift 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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 GRPC
  17. import Logging
  18. import XCTest
  19. /// This should be used instead of `XCTestCase`.
  20. class GRPCTestCase: XCTestCase {
  21. /// Unless `GRPC_ALWAYS_LOG` is set, logs will only be printed if a test case fails.
  22. private static let alwaysLog = Bool(
  23. fromTruthLike: ProcessInfo.processInfo.environment["GRPC_ALWAYS_LOG"],
  24. defaultingTo: false
  25. )
  26. private static let runTimeSensitiveTests = Bool(
  27. fromTruthLike: ProcessInfo.processInfo.environment["ENABLE_TIMING_TESTS"],
  28. defaultingTo: true
  29. )
  30. override func setUp() {
  31. super.setUp()
  32. self.logFactory = CapturingLogHandlerFactory(printWhenCaptured: GRPCTestCase.alwaysLog)
  33. }
  34. override func tearDown() {
  35. let logs = self.capturedLogs()
  36. // The default source emitted by swift-log is the directory containing the '#file' in which the
  37. // log was emitted. It's meant to represent the system which emitted the log, typically the
  38. // module name. In most cases it's right but in a few places, i.e. where the source lives in
  39. // child directories below 'GRPC', it isn't. We'll use this as a sanity check.
  40. //
  41. // See also: https://github.com/apple/swift-log/issues/145
  42. for log in logs {
  43. XCTAssertEqual(log.source, "GRPC", "Incorrect log source in \(log.file) on line \(log.line)")
  44. }
  45. // Only print logs when there's a failure and we're *not* always logging (when we are always
  46. // logging, logs will be printed as they're caught).
  47. if !GRPCTestCase.alwaysLog, (self.testRun.map { $0.totalFailureCount > 0 } ?? false) {
  48. self.printCapturedLogs(logs)
  49. }
  50. super.tearDown()
  51. }
  52. func runTimeSensitiveTests() -> Bool {
  53. let shouldRun = GRPCTestCase.runTimeSensitiveTests
  54. if !shouldRun {
  55. print("Skipping '\(self.name)' as ENABLE_TIMING_TESTS=false")
  56. }
  57. return shouldRun
  58. }
  59. private(set) var logFactory: CapturingLogHandlerFactory!
  60. /// A general-use logger.
  61. var logger: Logger {
  62. return Logger(label: "grpc", factory: self.logFactory.make)
  63. }
  64. /// A logger for clients to use.
  65. var clientLogger: Logger {
  66. // Label is ignored; we already have a handler.
  67. return Logger(label: "client", factory: self.logFactory.make)
  68. }
  69. /// A logger for servers to use.
  70. var serverLogger: Logger {
  71. // Label is ignored; we already have a handler.
  72. return Logger(label: "server", factory: self.logFactory.make)
  73. }
  74. /// The default client call options using `self.clientLogger`.
  75. var callOptionsWithLogger: CallOptions {
  76. return CallOptions(logger: self.clientLogger)
  77. }
  78. /// Returns all captured logs sorted by date.
  79. private func capturedLogs() -> [CapturedLog] {
  80. assert(self.logFactory != nil, "Missing call to super.setUp()")
  81. var logs = self.logFactory.clearCapturedLogs()
  82. logs.sort(by: { $0.date < $1.date })
  83. return logs
  84. }
  85. /// Prints all captured logs.
  86. private func printCapturedLogs(_ logs: [CapturedLog]) {
  87. print("Test Case '\(self.name)' logs started")
  88. // The logs are already sorted by date.
  89. let formatter = CapturedLogFormatter()
  90. for log in logs {
  91. print(formatter.string(for: log))
  92. }
  93. print("Test Case '\(self.name)' logs finished")
  94. }
  95. }
  96. extension Bool {
  97. fileprivate init(fromTruthLike value: String?, defaultingTo defaultValue: Bool) {
  98. switch value?.lowercased() {
  99. case "0", "false", "no":
  100. self = false
  101. case "1", "true", "yes":
  102. self = true
  103. default:
  104. self = defaultValue
  105. }
  106. }
  107. }