LocalData/Tests/LocalDataTests/Mocks/MockKeychainHelper.swift

45 lines
1.3 KiB
Swift

import Foundation
@testable import LocalData
/// A thread-safe mock implementation of KeychainStoring for unit tests.
/// Stores items in memory to avoid environmental entitlement issues.
public actor MockKeychainHelper: KeychainStoring {
private var storage: [String: Data] = [:]
public init() {}
public func set(
_ data: Data,
service: String,
key: String,
accessibility: KeychainAccessibility,
accessControl: KeychainAccessControl? = nil
) async throws {
storage[mockKey(service: service, key: key)] = data
}
public func get(service: String, key: String) async throws -> Data? {
storage[mockKey(service: service, key: key)]
}
public func delete(service: String, key: String) async throws {
storage.removeValue(forKey: mockKey(service: service, key: key))
}
public func exists(service: String, key: String) async throws -> Bool {
storage[mockKey(service: service, key: key)] != nil
}
public func deleteAll(service: String) async throws {
let prefix = "\(service)|"
storage.keys
.filter { $0.hasPrefix(prefix) }
.forEach { storage.removeValue(forKey: $0) }
}
private func mockKey(service: String, key: String) -> String {
"\(service)|\(key)"
}
}