import AppKit
import Foundation
import ParcelTestSupport
import Testing
@testable import ParcelUpdate
@MainActor
private final class Driver: UpdateDriver {
var canCheckForUpdates = true {
didSet { availabilityDidChange?() }
}
var availabilityDidChange: (@MainActor () -> Void)?
var availableVersion: String? { didSet { availabilityDidChange?() } }
var starts = 0
var checks = 0
var isReadyToRestart = false { didSet { availabilityDidChange?() } }
var restarts = 0
func restartToUpdate() -> Bool {
guard isReadyToRestart else { return false }
restarts += 1
return true
}
var failure: Failure?
func start() throws {
starts += 1
if let failure { throw failure }
}
func checkForUpdates() { checks += 1 }
}
private enum Failure: Error { case start }
@Suite @MainActor
struct UpdateControllerTests {
@Test func disabledNeverCreatesDriver() throws {
let updater = UpdateController(isEnabled: false) {
Issue.record("Disabled updates must not create a driver")
return Driver()
}
try updater.start()
#expect(!updater.isEnabled)
#expect(!updater.isStarted)
#expect(!updater.canCheckForUpdates)
#expect(!updater.checkForUpdates())
}
@Test func startsOnceAndGatesChecks() throws {
let driver = Driver()
let updater = UpdateController(isEnabled: true) { driver }
#expect(updater.isEnabled)
#expect(!updater.checkForUpdates())
try updater.start()
try updater.start()
#expect(updater.isStarted)
#expect(driver.starts == 1)
#expect(updater.canCheckForUpdates)
#expect(updater.checkForUpdates())
#expect(driver.checks == 1)
driver.canCheckForUpdates = false
#expect(!updater.canCheckForUpdates)
#expect(!updater.checkForUpdates())
#expect(driver.checks == 1)
driver.canCheckForUpdates = true
#expect(updater.checkForUpdates())
#expect(driver.checks == 2)
}
@Test func onlyDownloadedUpdatesCanRestartAndBusyChecksDoNotBlockInstallation() throws {
let driver = Driver()
let updater = UpdateController(isEnabled: true) { driver }
#expect(!updater.isReadyToRestart && !updater.restartToUpdate())
try updater.start()
driver.availableVersion = "2.0"
#expect(!updater.isReadyToRestart && !updater.restartToUpdate())
driver.canCheckForUpdates = false
driver.isReadyToRestart = true
#expect(updater.isReadyToRestart && updater.restartToUpdate())
#expect(driver.restarts == 1 && driver.checks == 0)
driver.isReadyToRestart = false
#expect(!updater.restartToUpdate())
}
@Test func readinessChangesNotifyObserversWithoutNetworking() throws {
let driver = Driver()
let updater = UpdateController(isEnabled: true) { driver }
var states: [Bool] = []
updater.availabilityDidChange = { states.append(updater.isReadyToRestart) }
try updater.start()
driver.availableVersion = "2.4"
driver.isReadyToRestart = true
driver.isReadyToRestart = false
#expect(states == [false, false, true, false])
}
@Test func startupFailureIsSurfacedAndCanRetry() throws {
let driver = Driver()
driver.failure = .start
let updater = UpdateController(isEnabled: true) { driver }
#expect(throws: Failure.start) { try updater.start() }
#expect(!updater.isStarted)
#expect(!updater.canCheckForUpdates)
driver.failure = nil
try updater.start()
#expect(updater.isStarted)
#expect(driver.starts == 2)
}
@Test func factoryFailureIsSurfaced() {
let updater = UpdateController(isEnabled: true) { throw Failure.start }
#expect(throws: Failure.start) { try updater.start() }
#expect(!updater.isStarted)
#expect(!updater.checkForUpdates())
}
#if DEBUG
@Test func liveDebugBuildIsDisabled() throws {
let updater = UpdateController.live()
try updater.start()
#expect(!updater.isEnabled)
#expect(!updater.isStarted)
#expect(!updater.checkForUpdates())
}
#endif
}
struct UpdateConfigurationTests {
private let key = Data(repeating: 7, count: 32).base64EncodedString()
@Test func acceptsSecureFeedAndEd25519Key() throws {
let configuration = try UpdateConfiguration(feedURL: "https://example.org/appcast.xml", publicKey: key)
#expect(configuration.feedURL.absoluteString == "https://example.org/appcast.xml")
#expect(configuration.publicKey == key)
}
@Test(
arguments: [
nil, "", "http://example.org/feed", "file:///feed", "https:///", "https://a:b@example.org/feed",
"https://example.org/feed#fragment", "https://example.org/a b",
] as [String?])
func rejectsInvalidFeed(feed: String?) {
#expect(throws: UpdateConfigurationError.invalidFeedURL) {
try UpdateConfiguration(feedURL: feed, publicKey: key)
}
}
@Test(
arguments: [
nil, "", "not base64", Data(repeating: 1, count: 31).base64EncodedString(),
Data(repeating: 1, count: 33).base64EncodedString(),
] as [String?])
func rejectsInvalidKey(key: String?) {
#expect(throws: UpdateConfigurationError.invalidPublicKey) {
try UpdateConfiguration(feedURL: "https://example.org/feed", publicKey: key)
}
}
@Test func missingBundleConfigurationFails() {
#expect(throws: UpdateConfigurationError.invalidFeedURL) { try UpdateConfiguration(bundle: .main) }
}
@Test(arguments: [nil, "SUFeedURL", "SUPublicEDKey"] as [String?])
func readsBundleConfigurationAndRejectsWrongTypes(invalidField: String?) throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("Update-\(UUID()).bundle")
let contents = root.appendingPathComponent("Contents")
try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)
defer {
do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) }
}
let feedValue =
invalidField == "SUFeedURL" ? "1" : "https://example.org/feed"
let keyValue = invalidField == "SUPublicEDKey" ? "1" : "\(key)"
let plist = """
CFBundleIdentifierdev.vinnymac.parcel.update-test.\(UUID())
SUFeedURL\(feedValue)
SUPublicEDKey\(keyValue)
"""
try Data(plist.utf8).write(to: contents.appendingPathComponent("Info.plist"))
let bundle = try #require(Bundle(url: root))
if let invalidField {
let error: UpdateConfigurationError = invalidField == "SUFeedURL" ? .invalidFeedURL : .invalidPublicKey
#expect(throws: error) { try UpdateConfiguration(bundle: bundle) }
} else {
let configuration = try UpdateConfiguration(bundle: bundle)
#expect(configuration.feedURL.absoluteString == "https://example.org/feed")
#expect(configuration.publicKey == key)
}
}
@Test(arguments: [UpdateConfigurationError.invalidFeedURL, .invalidPublicKey])
func errorsAreLocalized(error: UpdateConfigurationError) {
#expect(error.errorDescription?.isEmpty == false)
}
}
extension AppKitTestSuite {
@MainActor
struct UpdateControllerMenuTests {
init() { _ = NSApplication.shared }
@Test func menuItemSurvivesRebuildAndTracksAvailability() throws {
let driver = Driver()
let updater = UpdateController(isEnabled: true) { driver }
let menu = NSMenu()
menu.autoenablesItems = false
updater.installMenuItem(in: menu, at: 0)
let item = try #require(menu.items.first)
#expect(item.title == "Check for Updates…")
#expect(item.accessibilityLabel() == item.title)
#expect(item.keyEquivalent.isEmpty)
#expect(!item.isEnabled)
try updater.start()
#expect(item.isEnabled)
driver.canCheckForUpdates = false
#expect(!item.isEnabled)
driver.canCheckForUpdates = true
#expect(item.isEnabled)
updater.installMenuItem(in: menu, at: 0)
#expect(menu.numberOfItems == 1)
let rebuilt = NSMenu()
updater.installMenuItem(in: rebuilt, at: 0)
#expect(menu.numberOfItems == 0)
#expect(rebuilt.items.first === item)
let action = try #require(item.action)
#expect(NSApplication.shared.sendAction(action, to: item.target, from: item))
#expect(driver.checks == 1)
}
@Test func availableUpdateBecomesAnAccessibleActionAndClears() throws {
let driver = Driver()
let updater = UpdateController(isEnabled: true) { driver }
try updater.start()
let menu = NSMenu()
updater.installMenuItem(in: menu, at: 0)
driver.availableVersion = "1.2"
let item = try #require(menu.items.first)
#expect(updater.availableVersion == "1.2")
#expect(item.title == "Check for Updates…")
#expect(item.toolTip == "Update 1.2 Available…")
#expect(item.accessibilityLabel() == "Check for Updates…, update ready")
#expect(item.image != nil)
menu.performActionForItem(at: 0)
#expect(driver.checks == 1)
driver.canCheckForUpdates = false
#expect(!item.isEnabled)
driver.availableVersion = nil
#expect(item.title == "Check for Updates…")
#expect(item.image == nil)
}
@Test func installingBelowAnotherMenuDoesNotRelabelItsParent() throws {
let driver = Driver()
let updater = UpdateController(isEnabled: true) { driver }
let menu = NSMenu()
let parent = NSMenuItem(title: "Other", action: nil, keyEquivalent: "")
parent.setAccessibilityLabel("Other actions")
let root = NSMenu()
parent.submenu = menu
root.addItem(parent)
updater.installMenuItem(in: menu, at: 0)
try updater.start()
driver.availableVersion = "2.0"
#expect(parent.accessibilityLabel() == "Other actions")
#expect(parent.image == nil)
#expect(menu.items.first?.image != nil)
}
@Test func disabledMenuItemCannotStartARequest() throws {
let updater = UpdateController(isEnabled: false) { Driver() }
let menu = NSMenu()
updater.installMenuItem(in: menu, at: 0)
try updater.start()
#expect(menu.items.first?.isEnabled == false)
}
}
}