ReachabilityTests.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. let validHostName = "google.com"
  19. guard let reachability = Reachability(hostname: validHostName) else {
  20. XCTAssert(false, "Unable to create reachability")
  21. return
  22. }
  23. let expected = expectation(description: "Check valid host")
  24. reachability.whenReachable = { reachability in
  25. DispatchQueue.main.async {
  26. print("Pass: \(validHostName) is reachable - \(reachability)")
  27. // Only fulfill the expectation on host reachable
  28. expected.fulfill()
  29. }
  30. }
  31. reachability.whenUnreachable = { reachability in
  32. DispatchQueue.main.async {
  33. print("\(validHostName) is initially unreachable - \(reachability)")
  34. // Expectation isn't fulfilled here, so wait will time out if this is the only closure called
  35. }
  36. }
  37. do {
  38. try reachability.startNotifier()
  39. } catch {
  40. XCTAssert(false, "Unable to start notifier")
  41. return
  42. }
  43. waitForExpectations(timeout: 5, handler: nil)
  44. reachability.stopNotifier()
  45. }
  46. func testInvalidHost() {
  47. // Testing with an invalid host will initially show as reachable, but then the callback
  48. // gets fired a second time reporting the host as unreachable
  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. }