ReachabilityTests.swift 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. 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 reachability: Reachability
  21. let validHostName = "google.com"
  22. do {
  23. try reachability = Reachability(hostname: validHostName)
  24. } catch {
  25. XCTAssert(false, "Unable to create reachability")
  26. return
  27. }
  28. let expectation = expectationWithDescription("Check valid host")
  29. reachability.whenReachable = { reachability in
  30. dispatch_async(dispatch_get_main_queue()) {
  31. print("Pass: \(validHostName) is reachable - \(reachability)")
  32. // Only fulfill the expectaion on host reachable
  33. expectation.fulfill()
  34. }
  35. }
  36. reachability.whenUnreachable = { reachability in
  37. dispatch_async(dispatch_get_main_queue()) {
  38. print("\(validHostName) is initially unreachable - \(reachability)")
  39. // Expectation isn't fulfilled here, so wait will time out if this is the only closure called
  40. }
  41. }
  42. do {
  43. try reachability.startNotifier()
  44. } catch {
  45. XCTAssert(false, "Unable to start notifier")
  46. return
  47. }
  48. waitForExpectationsWithTimeout(5, handler: nil)
  49. reachability.stopNotifier()
  50. }
  51. func testInvalidHost() {
  52. let reachability: Reachability
  53. let invalidHostName = "invalidhost"
  54. do {
  55. try reachability = Reachability(hostname: invalidHostName)
  56. } catch {
  57. XCTAssert(false, "Unable to create reachability")
  58. return
  59. }
  60. let expectation = expectationWithDescription("Check invalid host")
  61. reachability.whenReachable = { reachability in
  62. dispatch_async(dispatch_get_main_queue()) {
  63. XCTAssert(false, "\(invalidHostName) should never be reachable - \(reachability))")
  64. }
  65. }
  66. reachability.whenUnreachable = { reachability in
  67. dispatch_async(dispatch_get_main_queue()) {
  68. print("Pass: \(invalidHostName) is unreachable - \(reachability))")
  69. expectation.fulfill()
  70. }
  71. }
  72. do {
  73. try reachability.startNotifier()
  74. } catch {
  75. XCTAssert(false, "Unable to start notifier")
  76. return
  77. }
  78. waitForExpectationsWithTimeout(5, handler: nil)
  79. reachability.stopNotifier()
  80. }
  81. }