Assertions.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 NIO
  18. /// Assertion error for interoperability testing.
  19. ///
  20. /// This is required because these tests must be able to run without XCTest.
  21. public struct AssertionError: Error {
  22. let message: String
  23. let file: StaticString
  24. let line: UInt
  25. }
  26. /// Asserts that the two given values are equal.
  27. public func assertEqual<T: Equatable>(
  28. _ value1: T,
  29. _ value2: T,
  30. file: StaticString = #file,
  31. line: UInt = #line
  32. ) throws {
  33. guard value1 == value2 else {
  34. throw AssertionError(message: "'\(value1)' is not equal to '\(value2)'", file: file, line: line)
  35. }
  36. }
  37. /// Waits for the future to be fulfilled and asserts that its value is equal to the given value.
  38. ///
  39. /// - Important: This should not be run on an event loop since this function calls `wait()` on the
  40. /// given future.
  41. public func waitAndAssertEqual<T: Equatable>(
  42. _ future: EventLoopFuture<T>,
  43. _ value: T,
  44. file: StaticString = #file,
  45. line: UInt = #line
  46. ) throws {
  47. try assertEqual(try future.wait(), value, file: file, line: line)
  48. }
  49. /// Waits for the futures to be fulfilled and ssserts that their values are equal.
  50. ///
  51. /// - Important: This should not be run on an event loop since this function calls `wait()` on the
  52. /// given future.
  53. public func waitAndAssertEqual<T: Equatable>(
  54. _ future1: EventLoopFuture<T>,
  55. _ future2: EventLoopFuture<T>,
  56. file: StaticString = #file,
  57. line: UInt = #line
  58. ) throws {
  59. try assertEqual(try future1.wait(), try future2.wait(), file: file, line: line)
  60. }
  61. public func waitAndAssert<T>(
  62. _ future: EventLoopFuture<T>,
  63. file: StaticString = #file,
  64. line: UInt = #line,
  65. message: String = "",
  66. verify: (T) -> Bool
  67. ) throws {
  68. let value = try future.wait()
  69. guard verify(value) else {
  70. throw AssertionError(message: message, file: file, line: line)
  71. }
  72. }