GRPCTestCase.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 XCTest
  17. import Logging
  18. /// A test case which initializes the logging system once.
  19. ///
  20. /// This should be used instead of `XCTestCase`.
  21. class GRPCTestCase: XCTestCase {
  22. // Travis will fail the CI if there is too much logging, but it can be useful when running
  23. // locally; conditionally enable it based on the environment.
  24. //
  25. // https://docs.travis-ci.com/user/environment-variables/#default-environment-variables
  26. private static var isLoggingEnabled = ProcessInfo.processInfo.environment["CI"] != "true"
  27. // `LoggingSystem.bootstrap` must be called once per process. This is the suggested approach to
  28. // workaround this for XCTestCase.
  29. //
  30. // See: https://github.com/apple/swift-log/issues/77
  31. private static let isLoggingConfigured: Bool = {
  32. LoggingSystem.bootstrap { label in
  33. guard isLoggingEnabled else {
  34. return BlackHole()
  35. }
  36. var handler = StreamLogHandler.standardOutput(label: label)
  37. handler.logLevel = .debug
  38. return handler
  39. }
  40. return true
  41. }()
  42. override class func setUp() {
  43. super.setUp()
  44. XCTAssertTrue(GRPCTestCase.isLoggingConfigured)
  45. }
  46. }
  47. /// A `LogHandler` which does nothing with log messages.
  48. struct BlackHole: LogHandler {
  49. func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) {
  50. ()
  51. }
  52. subscript(metadataKey key: String) -> Logger.Metadata.Value? {
  53. get {
  54. return metadata[key]
  55. }
  56. set(newValue) {
  57. self.metadata[key] = newValue
  58. }
  59. }
  60. var metadata: Logger.Metadata = [:]
  61. var logLevel: Logger.Level = .critical
  62. }