GRPCTestCase.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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()
  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. if GRPCTestCase.alwaysLog || (self.testRun.map { $0.totalFailureCount > 0 } ?? false) {
  46. self.printCapturedLogs(logs)
  47. }
  48. super.tearDown()
  49. }
  50. func runTimeSensitiveTests() -> Bool {
  51. let shouldRun = GRPCTestCase.runTimeSensitiveTests
  52. if !shouldRun {
  53. print("Skipping '\(self.name)' as ENABLE_TIMING_TESTS=false")
  54. }
  55. return shouldRun
  56. }
  57. private(set) var logFactory: CapturingLogHandlerFactory!
  58. /// A general-use logger.
  59. var logger: Logger {
  60. return Logger(label: "grpc", factory: self.logFactory.make)
  61. }
  62. /// A logger for clients to use.
  63. var clientLogger: Logger {
  64. // Label is ignored; we already have a handler.
  65. return Logger(label: "client", factory: self.logFactory.make)
  66. }
  67. /// A logger for servers to use.
  68. var serverLogger: Logger {
  69. // Label is ignored; we already have a handler.
  70. return Logger(label: "server", factory: self.logFactory.make)
  71. }
  72. /// The default client call options using `self.clientLogger`.
  73. var callOptionsWithLogger: CallOptions {
  74. return CallOptions(logger: self.clientLogger)
  75. }
  76. /// Returns all captured logs sorted by date.
  77. private func capturedLogs() -> [CapturedLog] {
  78. assert(self.logFactory != nil, "Missing call to super.setUp()")
  79. var logs = self.logFactory.clearCapturedLogs()
  80. logs.sort(by: { $0.date < $1.date })
  81. return logs
  82. }
  83. /// Prints all captured logs.
  84. private func printCapturedLogs(_ logs: [CapturedLog]) {
  85. let formatter = DateFormatter()
  86. // We don't care about the date.
  87. formatter.dateFormat = "HH:mm:ss.SSS"
  88. print("Test Case '\(self.name)' logs started")
  89. // The logs are already sorted by date.
  90. for log in logs {
  91. let date = formatter.string(from: log.date)
  92. let level = log.level.short
  93. // Format the metadata.
  94. let formattedMetadata = log.metadata
  95. .sorted(by: { $0.key < $1.key })
  96. .map { key, value in "\(key)=\(value)" }
  97. .joined(separator: " ")
  98. print("\(date) \(log.label) \(level):", log.message, formattedMetadata)
  99. }
  100. print("Test Case '\(self.name)' logs finished")
  101. }
  102. }
  103. extension Bool {
  104. fileprivate init(fromTruthLike value: String?, defaultingTo defaultValue: Bool) {
  105. switch value?.lowercased() {
  106. case "0", "false", "no":
  107. self = false
  108. case "1", "true", "yes":
  109. self = true
  110. default:
  111. self = defaultValue
  112. }
  113. }
  114. }
  115. extension Logger.Level {
  116. fileprivate var short: String {
  117. switch self {
  118. case .info:
  119. return "I"
  120. case .debug:
  121. return "D"
  122. case .warning:
  123. return "W"
  124. case .error:
  125. return "E"
  126. case .critical:
  127. return "C"
  128. case .trace:
  129. return "T"
  130. case .notice:
  131. return "N"
  132. }
  133. }
  134. }