ReachabilityTests.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. //
  2. // ReachabilityTests.swift
  3. // ReachabilityTests
  4. //
  5. // Created by Ashley Mills on 23/11/2015.
  6. // Copyright © 2015 Ashley Mills. All rights reserved.
  7. //
  8. import XCTest
  9. @testable import Reachability
  10. class ReachabilityTests: XCTestCase {
  11. override func setUp() {
  12. super.setUp()
  13. }
  14. override func tearDown() {
  15. super.tearDown()
  16. }
  17. func testValidHost() {
  18. // Testing with an invalid host will initially show as UNreachable, but then the callback
  19. // gets fired a second time reporting the host as reachable
  20. let validHostName = "google.com"
  21. guard let reachability = Reachability(hostname: validHostName) else {
  22. XCTAssert(false, "Unable to create reachability")
  23. return
  24. }
  25. let expected = expectation(description: "Check valid host")
  26. reachability.whenReachable = { reachability in
  27. DispatchQueue.main.async {
  28. print("Pass: \(validHostName) is reachable - \(reachability)")
  29. // Only fulfill the expectation on host reachable
  30. expected.fulfill()
  31. }
  32. }
  33. reachability.whenUnreachable = { reachability in
  34. DispatchQueue.main.async {
  35. print("\(validHostName) is initially unreachable - \(reachability)")
  36. // Expectation isn't fulfilled here, so wait will time out if this is the only closure called
  37. }
  38. }
  39. do {
  40. try reachability.startNotifier()
  41. } catch {
  42. XCTAssert(false, "Unable to start notifier")
  43. return
  44. }
  45. waitForExpectations(timeout: 5, handler: nil)
  46. reachability.stopNotifier()
  47. }
  48. func testInvalidHost() {
  49. let invalidHostName = "invalidhost"
  50. guard let reachability = Reachability(hostname: invalidHostName) else {
  51. XCTAssert(false, "Unable to create reachability")
  52. return
  53. }
  54. let expected = expectation(description: "Check invalid host")
  55. reachability.whenReachable = { reachability in
  56. DispatchQueue.main.async {
  57. XCTAssert(false, "\(invalidHostName) should never be reachable - \(reachability))")
  58. }
  59. }
  60. reachability.whenUnreachable = { reachability in
  61. DispatchQueue.main.async {
  62. print("Pass: \(invalidHostName) is unreachable - \(reachability))")
  63. expected.fulfill()
  64. }
  65. }
  66. do {
  67. try reachability.startNotifier()
  68. } catch {
  69. XCTAssert(false, "Unable to start notifier")
  70. return
  71. }
  72. waitForExpectations(timeout: 5, handler: nil)
  73. reachability.stopNotifier()
  74. }
  75. }