2
0

Assertions.swift 2.4 KB

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