fix(menubar): 修正进程退出判断与公网刷新及风扇语言
This commit is contained in:
@@ -30,6 +30,12 @@ import Foundation
|
||||
let value = AppLocalization.string(key, locale: locale, bundle: bundle, table: table)
|
||||
precondition(!value.isEmpty && value != key, "Missing built translation: \(language)/\(table)/\(key)")
|
||||
}
|
||||
for number in [1, 3, 10] {
|
||||
let format = AppLocalization.string("gpu.fanNumber %lld", locale: locale, bundle: bundle)
|
||||
let title = String(format: format, Int64(number))
|
||||
let expected = ["en": "Fan", "zh-Hans": "风扇", "zh-Hant": "風扇"][language]!
|
||||
precondition(title == "\(expected) \(number)", "Numbered fan must use the selected app locale")
|
||||
}
|
||||
let average = AppLocalization.string("gpu.recentAverage", locale: locale, bundle: bundle)
|
||||
precondition(average == ["en": "Last-minute average", "zh-Hans": "近 1 分钟平均", "zh-Hant": "近 1 分鐘平均"][language])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import Foundation
|
||||
|
||||
@main struct ProcessSelectionChecks {
|
||||
static func main() {
|
||||
let id = ProcessIdentity(pid: 42, seconds: 100, microseconds: 0)
|
||||
let row = ProcessMetrics(id: id, name: "worker", path: "/test/worker", cpu: 0.2,
|
||||
residentBytes: 10, threads: 1, restricted: false)
|
||||
let live = ProcessSnapshot(date: Date(), enumerated: 1, readable: 1, rows: [row], failed: false)
|
||||
let filtered = ProcessTableProjection.rows(live.rows, query: "does-not-match", sorting: [], order: [])
|
||||
precondition(filtered.isEmpty)
|
||||
precondition(ProcessTableProjection.exitedSelection(id, in: live) == nil, "Filtered selection is still alive")
|
||||
precondition(ProcessTableProjection.exitedSelection(nil, in: live) == nil)
|
||||
precondition(ProcessTableProjection.exitedSelection(id, in: nil) == nil)
|
||||
let failed = ProcessSnapshot(date: Date(), enumerated: 0, readable: 0, rows: [], failed: true)
|
||||
precondition(ProcessTableProjection.exitedSelection(id, in: failed) == nil, "A failed read cannot prove exit")
|
||||
let exited = ProcessSnapshot(date: Date(), enumerated: 0, readable: 0, rows: [], failed: false)
|
||||
precondition(ProcessTableProjection.exitedSelection(id, in: exited) == id)
|
||||
let reused = ProcessIdentity(pid: 42, seconds: 101, microseconds: 0)
|
||||
let replacement = ProcessMetrics(id: reused, name: row.name, path: row.path, cpu: nil,
|
||||
residentBytes: nil, threads: nil, restricted: true)
|
||||
let recycled = ProcessSnapshot(date: Date(), enumerated: 1, readable: 0, rows: [replacement], failed: false)
|
||||
precondition(ProcessTableProjection.exitedSelection(id, in: recycled) == id, "PID reuse cannot keep the previous process alive")
|
||||
precondition(ProcessTableProjection.exitedSelection(reused, in: recycled) == nil)
|
||||
print("PASS: filtered/live selection, absent selection/snapshot, failed enumeration, actual exit and PID reuse")
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,151 @@
|
||||
import Foundation
|
||||
|
||||
final class IPResponse: URLProtocol, @unchecked Sendable {
|
||||
nonisolated(unsafe) static var payload = "203.0.113.4"
|
||||
nonisolated(unsafe) static var status = 200
|
||||
nonisolated(unsafe) static var count = 0
|
||||
private final class ResponseState: @unchecked Sendable {
|
||||
enum Response { case success(String), httpFailure, timeout, pending }
|
||||
private let lock = NSLock()
|
||||
private var response = Response.success("203.0.113.4")
|
||||
private var requests = 0
|
||||
private var stops = 0
|
||||
func configure(_ value: Response) { lock.lock(); defer { lock.unlock() }; response = value }
|
||||
func begin() -> Response { lock.lock(); defer { lock.unlock() }; requests += 1; return response }
|
||||
func stopped() { lock.lock(); defer { lock.unlock() }; stops += 1 }
|
||||
var count: Int { lock.lock(); defer { lock.unlock() }; return requests }
|
||||
var cancellations: Int { lock.lock(); defer { lock.unlock() }; return stops }
|
||||
}
|
||||
|
||||
private final class IPResponse: URLProtocol, @unchecked Sendable {
|
||||
static let state = ResponseState()
|
||||
override class func canInit(with request: URLRequest) -> Bool { true }
|
||||
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
||||
override func startLoading() {
|
||||
Self.count += 1
|
||||
precondition(request.url?.scheme == "https" && request.timeoutInterval == 5)
|
||||
client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: Self.status, httpVersion: nil, headerFields: nil)!, cacheStoragePolicy: .notAllowed)
|
||||
client?.urlProtocol(self, didLoad: Data(Self.payload.utf8))
|
||||
let response = Self.state.begin()
|
||||
switch response {
|
||||
case .pending: return
|
||||
case .timeout:
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.timedOut))
|
||||
case .success(let payload): deliver(payload, status: 200)
|
||||
case .httpFailure: deliver("unavailable", status: 503)
|
||||
}
|
||||
}
|
||||
private func deliver(_ payload: String, status: Int) {
|
||||
client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!, cacheStoragePolicy: .notAllowed)
|
||||
client?.urlProtocol(self, didLoad: Data(payload.utf8))
|
||||
client?.urlProtocolDidFinishLoading(self)
|
||||
}
|
||||
override func stopLoading() {}
|
||||
override func stopLoading() { Self.state.stopped() }
|
||||
}
|
||||
|
||||
private final class TestClock: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var value: TimeInterval = 0
|
||||
func advance(_ seconds: TimeInterval) { lock.lock(); defer { lock.unlock() }; value += seconds }
|
||||
func now() -> TimeInterval { lock.lock(); defer { lock.unlock() }; return value }
|
||||
}
|
||||
|
||||
private actor Deliveries {
|
||||
private var values: [String?] = []
|
||||
func receive(_ value: String?) { values.append(value) }
|
||||
var count: Int { values.count }
|
||||
var last: String? { values.last ?? nil }
|
||||
}
|
||||
|
||||
@main struct PublicIPAddressChecks {
|
||||
static func main() async {
|
||||
static func main() async throws {
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.protocolClasses = [IPResponse.self]
|
||||
let session = URLSession(configuration: config)
|
||||
defer { session.invalidateAndCancel() }
|
||||
let service = PublicIPAddressService(session: session)
|
||||
let clock = TestClock()
|
||||
let service = PublicIPAddressService(session: session, now: { clock.now() })
|
||||
let first = await service.address(route: "one")
|
||||
precondition(first == "203.0.113.4")
|
||||
let initialCount = IPResponse.state.count
|
||||
clock.advance(599)
|
||||
let cached = await service.address(route: "one")
|
||||
precondition(cached == first && IPResponse.count == 1)
|
||||
IPResponse.payload = "2001:db8::1"
|
||||
precondition(cached == first && IPResponse.state.count == initialCount)
|
||||
clock.advance(1)
|
||||
IPResponse.state.configure(.success("203.0.113.5"))
|
||||
let expired = await service.address(route: "one")
|
||||
precondition(expired == "203.0.113.5" && IPResponse.state.count == initialCount + 1)
|
||||
IPResponse.state.configure(.success("2001:db8::1"))
|
||||
let changed = await service.address(route: "two")
|
||||
precondition(changed == "2001:db8::1" && IPResponse.count == 2)
|
||||
IPResponse.payload = "<html>invalid</html>"
|
||||
precondition(changed == "2001:db8::1")
|
||||
IPResponse.state.configure(.success("<html>invalid</html>"))
|
||||
let invalid = await service.address(route: "three")
|
||||
precondition(invalid == nil)
|
||||
let failedCount = IPResponse.state.count
|
||||
IPResponse.state.configure(.success("203.0.113.4"))
|
||||
clock.advance(29)
|
||||
let cachedFailure = await service.address(route: "three")
|
||||
precondition(cachedFailure == nil && IPResponse.count == 3)
|
||||
IPResponse.payload = "203.0.113.4"
|
||||
IPResponse.status = 503
|
||||
precondition(cachedFailure == nil && IPResponse.state.count == failedCount)
|
||||
clock.advance(1)
|
||||
let recovered = await service.address(route: "three")
|
||||
precondition(recovered == "203.0.113.4" && IPResponse.state.count == failedCount + 1)
|
||||
IPResponse.state.configure(.httpFailure)
|
||||
let httpFailure = await service.address(route: "four")
|
||||
precondition(httpFailure == nil)
|
||||
print("PASS: IPv4/IPv6, route cache, invalid payload, cached failure, HTTP failure, timeout")
|
||||
IPResponse.state.configure(.timeout)
|
||||
let timedOut = await service.address(route: "five")
|
||||
precondition(timedOut == nil)
|
||||
clock.advance(30)
|
||||
IPResponse.state.configure(.success("203.0.113.6"))
|
||||
let afterTimeout = await service.address(route: "five")
|
||||
precondition(afterTimeout == "203.0.113.6")
|
||||
|
||||
// Exercise the same continuous-refresh function used by the SwiftUI task.
|
||||
// Short intervals keep this integration check fast; cache-boundary checks above use a fake clock.
|
||||
let looping = PublicIPAddressService(session: session, cacheLifetime: 0.04, retryInterval: 0.02)
|
||||
let deliveries = Deliveries()
|
||||
IPResponse.state.configure(.timeout)
|
||||
let loop = Task { await looping.refreshContinuously(route: "visible") { await deliveries.receive($0) } }
|
||||
try await until { await deliveries.count >= 1 }
|
||||
IPResponse.state.configure(.success("203.0.113.7"))
|
||||
try await until { await deliveries.last == "203.0.113.7" }
|
||||
IPResponse.state.configure(.success("203.0.113.8"))
|
||||
try await until { await deliveries.last == "203.0.113.8" }
|
||||
loop.cancel()
|
||||
await loop.value
|
||||
let stoppedCount = IPResponse.state.count
|
||||
let stoppedDeliveries = await deliveries.count
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
let finalDeliveries = await deliveries.count
|
||||
precondition(IPResponse.state.count == stoppedCount && finalDeliveries == stoppedDeliveries,
|
||||
"Hidden/cancelled observers must stop polling and publishing")
|
||||
|
||||
IPResponse.state.configure(.pending)
|
||||
let beforeCancel = IPResponse.state.count
|
||||
let pending = Task { await service.address(route: "cancelled-route") }
|
||||
try await until { IPResponse.state.count > beforeCancel }
|
||||
let previousStops = IPResponse.state.cancellations
|
||||
pending.cancel()
|
||||
let cancelled = await pending.value
|
||||
precondition(cancelled == nil)
|
||||
try await until { IPResponse.state.cancellations > previousStops }
|
||||
IPResponse.state.configure(.success("203.0.113.9"))
|
||||
let afterCancellation = await service.address(route: "cancelled-route")
|
||||
precondition(afterCancellation == "203.0.113.9", "Cancellation must not cache a failure")
|
||||
let cancelledDeliveries = Deliveries()
|
||||
IPResponse.state.configure(.pending)
|
||||
let beforeObserver = IPResponse.state.count
|
||||
let oldRoute = Task {
|
||||
await service.refreshContinuously(route: "old-visible-route") { await cancelledDeliveries.receive($0) }
|
||||
}
|
||||
try await until { IPResponse.state.count > beforeObserver }
|
||||
oldRoute.cancel()
|
||||
await oldRoute.value
|
||||
let cancelledCount = await cancelledDeliveries.count
|
||||
precondition(cancelledCount == 0, "A cancelled route must never publish its pending response")
|
||||
IPResponse.state.configure(.success("203.0.113.10"))
|
||||
let newRoute = await service.address(route: "new-visible-route")
|
||||
precondition(newRoute == "203.0.113.10")
|
||||
print("PASS: IPv4/IPv6, route changes, 600s expiry, 30s failure retry, invalid payload, HTTP failure, simulated transport timeout/recovery, continuous refresh and cancellation")
|
||||
}
|
||||
|
||||
private static func until(_ predicate: () async -> Bool) async throws {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||
while !(await predicate()) && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(2)) }
|
||||
let passed = await predicate()
|
||||
precondition(passed, "Timed out waiting for network test event")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user