Thank you for your answer!
Below is my code and my error condition.
Target : my project
File: Keychain.swift:
Code:
private let SecMatchLimit: String! = kSecMatchLimit as String
private let SecReturnData: String! = kSecReturnData as String
private let SecValueData: String! = kSecValueData as String
private let SecClass: String! = kSecClass as String
private let SecAttrGeneric: String! = kSecAttrGeneric as String
private let SecAttrAccount: String! = kSecAttrAccount as String
class Keychain {
@discardableResult
static func save(key: String, data: Data) -> Bool {
let query = [
SecClass: kSecClassGenericPassword as String,
SecAttrAccount: key,
SecValueData: data ] as [String : Any]
SecItemDelete(query as CFDictionary)
let status: OSStatus = SecItemAdd(query as CFDictionary, nil)
if status == errSecSuccess {
return true
} else if status == errSecDuplicateItem {
return update(data, forKey: key)
} else {
return false
}
}
}
Target : myprojectTests
File: KeychainTests.swift:
Code:
class KeychainTests: XCTestCase {
func testSaveData() {
let key = "foo"
guard let data = "data".data(using: .utf8) else {
fatalError()
}
let result = Keychain.save(key: key, data: data)
XCTAssertTrue(result, "key chain save data failure")
let saveData = Keychain.loadData(key: key)
XCTAssertNotNil(saveData, "saveData is nil")
guard let sd = saveData else {
fatalError("Keyhain load failure")
}
XCTAssertEqual(sd, data, "save data is not equal to load data")
guard let updateData = "data2".data(using: .utf8) else {
fatalError()
}
Keychain.save(key: key, data: updateData)
let updateDataFromKeychain = Keychain.loadData(key: key)
XCTAssertNotNil(updateDataFromKeychain, "updateDataFromKeychain is nil")
guard let uData = updateDataFromKeychain else { fatalError("Keychain load failure") }
XCTAssertEqual(uData, updateData, "update data is not equal to load update data")
}
}
```
The test function was passed in the Xcode8.3 and the unit test target's Host Application is none.I can use xctool run-tests it without simulator.
And Xcode9 run test with Host Application of none, Nothing else has been touched.The unit test is always failure, and the SecItemAdd function is always failure, the error OSStatus is -50.I have to change Host Application to my project , it can be run pass.It is my problem, I like to use xctool to test my project unit test without simulator, so I hope Xcode can be re-add the Keychain unit test when Host Application is none.This is just my personal opinion.
Thanks again!