Open History to see the last commit
1import Foundation
2
3enum NWInterface {
4 enum InterfaceType {
5 case other, wifi, cellular, loopback, wiredEthernet
6 }
7}
8
9struct NWPath {
10 enum Status {
11 case satisfied, unsatisfied
12 }
13
14 // A reference inside the value models the native path's retained storage.
15 final class Storage {
16 let type: NWInterface.InterfaceType
17 init(_ type: NWInterface.InterfaceType) { self.type = type }
18 }
19
20 let status: Status
21 let storage: Storage
22
23 init(_ type: NWInterface.InterfaceType, status: Status = .satisfied) {
24 self.status = status
25 storage = Storage(type)
26 }
27
28 func usesInterfaceType(_ type: NWInterface.InterfaceType) -> Bool {
29 storage.type == type
30 }
31}
32
33final class NWPathMonitor {
34 static var scenario = "first"
35 static let deliveries = DispatchGroup()
36 var pathUpdateHandler: ((NWPath) -> Void)?
37
38 func start(queue: DispatchQueue) {
39 guard let handler = pathUpdateHandler else { fatalError("Missing path handler") }
40 if Self.scenario == "offline" {
41 handler(NWPath(.wifi, status: .unsatisfied))
42 } else if Self.scenario == "first" {
43 handler(NWPath(.wifi))
44 handler(NWPath(.cellular))
45 } else {
46 queue.async(group: Self.deliveries) {
47 handler(NWPath(.wifi))
48 DispatchQueue.concurrentPerform(iterations: 128) { index in
49 handler(NWPath(index.isMultiple(of: 2) ? .cellular : .wiredEthernet))
50 }
51 }
52 }
53 }
54
55 // Already queued callbacks can run after cancellation.
56 func cancel() {}
57}
58
59@main
60enum NetworkModuleRegression {
61 static func main() {
62 NWPathMonitor.scenario = CommandLine.arguments[1]
63 let module = NetworkModule()
64 if NWPathMonitor.scenario == "concurrent" {
65 DispatchQueue.concurrentPerform(iterations: 64) { _ in
66 let state = module.getNetworkStateAsync()
67 precondition(state["type"] as? String == "WIFI", "The first path must survive late callbacks")
68 precondition(state["isConnected"] as? Bool == true)
69 }
70 NWPathMonitor.deliveries.wait()
71 } else {
72 let state = module.getNetworkStateAsync()
73 let connected = NWPathMonitor.scenario != "offline"
74 precondition(state["type"] as? String == (connected ? "WIFI" : "NONE"))
75 precondition(state["isConnected"] as? Bool == connected)
76 precondition(state["isInternetReachable"] as? Bool == connected)
77 }
78 print("passed")
79 }
80}