ReachabilityTests.swift 2.3 KB

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