Skip to content

Commit

Permalink
Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcin Grześkowiak committed Nov 7, 2024
1 parent fce5d35 commit 7e38749
Show file tree
Hide file tree
Showing 12 changed files with 58 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ final class RequestBuilderTests: XCTestCase {
// MARK: Session Service Request

func testUserContextFromTokensRequestWrongURL() throws {
let sessionURL = URL("https://example.com")
let sessionURL = URL(staticString: "https://example.com")
let expectedURL = sessionURL.appendingPathComponent("/bad/path")

let sut = RequestBuilder.userContextFromToken
Expand All @@ -195,7 +195,7 @@ final class RequestBuilderTests: XCTestCase {

func testCodeExchangeAsRequestExpectedURL() throws {
let expectedClientId = "aString"
let baseURL = URL("https://example.com")
let baseURL = URL(staticString: "https://example.com")
let expectedURL = baseURL.appendingPathComponent("/api/2/oauth/exchange")

let sut = RequestBuilder.codeExchange(clientId: expectedClientId)
Expand All @@ -205,7 +205,7 @@ final class RequestBuilderTests: XCTestCase {

func testCodeExchangeAsRequestWrongURL() throws {
let expectedClientId = "aString"
let baseURL = URL("https://example.com")
let baseURL = URL(staticString: "https://example.com")
let expectedURL = baseURL.appendingPathComponent("/bad/path")

let sut = RequestBuilder.codeExchange(clientId: expectedClientId)
Expand All @@ -216,7 +216,7 @@ final class RequestBuilderTests: XCTestCase {
// MARK: OldSDKRefreshToken tests

func testOldSDKRefreshTokenAsRequestExpectedURL() throws {
let baseURL = URL("https://example.com")
let baseURL = URL(staticString: "https://example.com")
let expectedURL = baseURL.appendingPathComponent("/oauth/token")
let expectedRefreshToken = "A refreshToken"

Expand All @@ -226,7 +226,7 @@ final class RequestBuilderTests: XCTestCase {
}

func testOldSDKRefreshTokenAsRequestWrongURL() throws {
let baseURL = URL("https://example.com")
let baseURL = URL(staticString: "https://example.com")
let expectedURL = baseURL.appendingPathComponent("/bad/path")
let expectedRefreshToken = "A refreshToken"

Expand All @@ -238,7 +238,7 @@ final class RequestBuilderTests: XCTestCase {
// MARK: Session Service Request

func testAssertionForSimplifiedLoginAsRequestExpectedURL() throws {
let baseURL = URL("https://example.com")
let baseURL = URL(staticString: "https://example.com")
let expectedURL = baseURL.appendingPathComponent("/api/2/user/auth/token")

let sut = RequestBuilder.assertionForSimplifiedLogin
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import XCTest

extension XCTWaiter.Result: CustomStringConvertible {
extension XCTWaiter.Result: @retroactive CustomStringConvertible {
public var description: String {
let state: String
switch self {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ final class ClientTests: XCTestCase {
let client = Client(configuration: Fixtures.clientConfig, sessionStorage: MockSessionStorage(), stateStorage: StateStorage(storage: mockStorage))

Await.until { done in
client.handleAuthenticationResponse(url: URL("com.example://login?state=no-exist&code=123456")) { result in
client.handleAuthenticationResponse(url: URL(staticString: "com.example://login?state=no-exist&code=123456")) { result in
XCTAssertEqual(result, .failure(.unsolicitedResponse))
done()
}
Expand Down Expand Up @@ -86,9 +86,7 @@ final class ClientTests: XCTestCase {

let mockSessionStorage = MockSessionStorage()
stub(mockSessionStorage) { mock in
when(mock.store(any(), accessGroup: any(), completion: anyClosure())).then {_, _, completion in
completion(.success())
}
when(mock.store(any(), accessGroup: any())).then {_ in }
}
let state = "testState"
let mockStorage = MockStorage()
Expand All @@ -112,7 +110,7 @@ final class ClientTests: XCTestCase {
func testHandleAuthenticationResponseHandlesTokenErrorResponse() {
let mockSessionStorage = MockSessionStorage()
stub(mockSessionStorage) { mock in
when(mock.store(any(), accessGroup: any(), completion: anyClosure())).thenDoNothing()
when(mock.store(any(), accessGroup: any())).thenDoNothing()
}
let state = "testState"
let mockStorage = MockStorage()
Expand Down Expand Up @@ -196,7 +194,7 @@ final class ClientTests: XCTestCase {
let client = Client(configuration: Fixtures.clientConfig, sessionStorage: MockSessionStorage(), stateStorage: StateStorage(storage: mockStorage))

Await.until { done in
client.handleAuthenticationResponse(url: URL("com.example:/cancel")) { result in
client.handleAuthenticationResponse(url: URL(staticString: "com.example:/cancel")) { result in
XCTAssertEqual(result, .failure(.canceled))
done()
}
Expand Down Expand Up @@ -269,9 +267,7 @@ final class ClientTests: XCTestCase {
let mockSessionStorage = MockSessionStorage()

stub(mockSessionStorage) { mock in
when(mock.store(any(), accessGroup: any(), completion: anyClosure())).then {_, _, completion in
completion(.success())
}
when(mock.store(any(), accessGroup: any())).then {_ in }
}
let stateStorage = StateStorage(storage: MockStorage())

Expand All @@ -288,7 +284,7 @@ final class ClientTests: XCTestCase {
XCTFail("Unexprected error \(error.localizedDescription)")
}
}
verify(mockSessionStorage, times(1)).store(any(), accessGroup: any(), completion: any())
verify(mockSessionStorage, times(1)).store(any(), accessGroup: any())
}

func testRetryStoringToKeychainInCaseOfFailure() {
Expand All @@ -306,8 +302,8 @@ final class ClientTests: XCTestCase {
let mockSessionStorage = MockSessionStorage()

stub(mockSessionStorage) { mock in
when(mock.store(any(), accessGroup: any(), completion: anyClosure())).then {_, _, completion in
completion(.failure(KeychainStorageError.operationError))
when(mock.store(any(), accessGroup: any())).then { _ in
throw KeychainStorageError.operationError
}
}
let stateStorage = StateStorage(storage: MockStorage())
Expand All @@ -324,7 +320,7 @@ final class ClientTests: XCTestCase {
XCTAssertEqual(String(describing: error), "unexpectedError(error: AccountSDKIOSWeb.KeychainStorageError.operationError)")
}
}
verify(mockSessionStorage, times(2)).store(any(), accessGroup: any(), completion: any())
verify(mockSessionStorage, times(2)).store(any(), accessGroup: any())
}

func testSuccessfullSecondAttemptToStoreSessionTokens() {
Expand All @@ -343,12 +339,10 @@ final class ClientTests: XCTestCase {
let mockSessionStorage = MockSessionStorage()

stub(mockSessionStorage) { mock in
when(mock.store(any(), accessGroup: any(), completion: anyClosure())).then {_, _, completion in
when(mock.store(any(), accessGroup: any())).then {_ in
if isFirst {
isFirst = false
completion(.failure(KeychainStorageError.operationError))
} else {
completion(.success())
throw KeychainStorageError.operationError
}
}
}
Expand All @@ -367,7 +361,7 @@ final class ClientTests: XCTestCase {
XCTFail("Unexprected error \(error.localizedDescription)")
}
}
verify(mockSessionStorage, times(2)).store(any(), accessGroup: any(), completion: any())
verify(mockSessionStorage, times(2)).store(any(), accessGroup: any())
}

func testGetExternalId() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Foundation
@testable import AccountSDKIOSWeb

struct Fixtures {
static let clientConfig = ClientConfiguration(env: .pre, serverURL: URL(string: "https://issuer.example.com")!, sessionServiceURL: URL(string: "https://another.issuer.example.com")!, clientId: "client1", redirectURI: URL("com.example.client1://login"))
static let clientConfig = ClientConfiguration(env: .pre, serverURL: URL(staticString: "https://issuer.example.com"), sessionServiceURL: URL(staticString: "https://another.issuer.example.com"), clientId: "client1", redirectURI: URL(staticString: "com.example.client1://login"))
static let idTokenClaims = IdTokenClaims(iss: clientConfig.issuer, sub: "userUuid", userId: "12345", aud: ["client1"], exp: Date().timeIntervalSince1970 + 3600, nonce: "testNonce", amr: nil)
static let userTokens = UserTokens(accessToken: "accessToken", refreshToken: "refreshToken", idToken: "idToken", idTokenClaims: Fixtures.idTokenClaims)

Expand Down Expand Up @@ -43,9 +43,9 @@ struct TestResponse: Codable, Equatable {
}

extension URL {
init(_ string: StaticString) {
guard let url = URL(string: "\(string)") else {
preconditionFailure("Invalid static URL string: \(string)")
init(staticString: StaticString) {
guard let url = URL(string: "\(staticString)") else {
preconditionFailure("Invalid static URL string: \(staticString)")
}

self = url
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Cuckoo

final class AccountSDKIOSWebTests: XCTestCaseWithMockHTTPClient {

let testURL = URL("http://www.example.com")
let testURL = URL(staticString: "http://www.example.com")
let testConfig : URLSessionConfiguration = {
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [MockURLProtocol.self]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private class TestRetryPolicy: RetryPolicy {
final class HTTPClientWithURLSessionTests: XCTestCase {

func testDoesntRetrySuccessfulRequest() throws {
let request = URLRequest(url: URL("https://example.com"))
let request = URLRequest(url: URL(staticString: "https://example.com"))
let expectedResponse = TestResponse(data: "Hello world!")

let urlResponse = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)
Expand All @@ -44,7 +44,7 @@ final class HTTPClientWithURLSessionTests: XCTestCase {
}

func testRetriesFailedRequest() throws {
let request = URLRequest(url: URL("https://example.com"))
let request = URLRequest(url: URL(staticString: "https://example.com"))
let expectedResponse = TestResponse(data: "Hello world!")

let failedRequestResult: (Data?, HTTPURLResponse?, Error?) = (nil, nil, URLError(.cannotConnectToHost))
Expand All @@ -66,7 +66,7 @@ final class HTTPClientWithURLSessionTests: XCTestCase {
}

func testRetries5xxRequest() throws {
let request = URLRequest(url: URL("https://example.com"))
let request = URLRequest(url: URL(staticString: "https://example.com"))
let expectedResponse = TestResponse(data: "Hello world!")

let failedUrlResponse = HTTPURLResponse(url: request.url!, statusCode: 502, httpVersion: "HTTP/1.1", headerFields: nil)
Expand All @@ -89,7 +89,7 @@ final class HTTPClientWithURLSessionTests: XCTestCase {
}

func testDontRetryFailedRequestIfNoRetriesPolicy() throws {
let request = URLRequest(url: URL("https://example.com"))
let request = URLRequest(url: URL(staticString: "https://example.com"))

let failureResults: [(Data?, HTTPURLResponse?, Error?)] = [
(nil, nil, URLError(.cannotConnectToHost)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ private class DictionaryCache<V>: Cache<V> {
}

final class RemoteJWKSTests: XCTestCase {
private let jwksURI = URL("https://example.com/jwks")
private let jwksURI = URL(staticString: "https://example.com/jwks")
private let testJWK = RSAPublicKey(modulus: "aaa", exponent: "bbb")

func testGetKeyReturnsAlreadyCachedKey() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ struct MockSessionStorageProtocol: SessionStorage {
return sessions
}

func store(_ value: UserSession, accessGroup: String?, completion: @escaping (Result<Void, Error>) -> Void) { }
func get(forClientId: String, completion: @escaping (UserSession?) -> Void) { }
func store(_ value: AccountSDKIOSWeb.UserSession, accessGroup: String?) throws { }
func get(forClientId: String) -> AccountSDKIOSWeb.UserSession? { return nil }
func remove(forClientId: String) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Foundation
import XCTest
@testable import AccountSDKIOSWeb

private class FakeDataTask: URLSessionDataTask {
private class FakeDataTask: URLSessionDataTask, @unchecked Sendable {
private let completionHandler: () -> Void

init(completionHandler: @escaping () -> Void) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ final class SharedKeychainSessionStorageFactoryTests: XCTestCase {
}
let keychainSessionStorageMock = MockKeychainSessionStorage(service: "service_name", accessGroup: accessGroup)
stub(keychainSessionStorageMock) { mock in
when(mock.get(forClientId: "client_id", completion: anyClosure()))
.then { _, completion in
completion(userSession)
when(mock.get(forClientId: "client_id"))
.then { _ in
userSession
}
}

Expand All @@ -65,7 +65,7 @@ final class SharedKeychainSessionStorageFactoryTests: XCTestCase {
XCTAssertIdentical(keychain, sharedKeychainSessionStorageMock)
verify(sharedKeychainSessionStorageMock).checkEntitlements()
verify(sharedKeychainSessionStorageMock).getAll()
verify(sharedKeychainSessionStorageMock, never()).store(any(), accessGroup: sharedAccessGroup, completion: anyClosure())
verify(sharedKeychainSessionStorageMock, never()).store(any(), accessGroup: sharedAccessGroup)
}

func testReturnsSharedKeychainWithUpdatedAccessGroupForItem() {
Expand All @@ -75,19 +75,16 @@ final class SharedKeychainSessionStorageFactoryTests: XCTestCase {
when(mock.checkEntitlements()).then { _ in
return Data()
}
when(mock.store(any(), accessGroup: sharedAccessGroup, completion: anyClosure()))
.then { _, _, completion in
completion(.success())
}
when(mock.store(any(), accessGroup: sharedAccessGroup)).then { _ in }
when(mock.getAll()).then { _ in
return []
}
}
let keychainSessionStorageMock = MockKeychainSessionStorage(service: "service_name", accessGroup: accessGroup)
stub(keychainSessionStorageMock) { mock in
when(mock.get(forClientId: "client_id", completion: anyClosure()))
.then { _, completion in
completion(userSession)
when(mock.get(forClientId: "client_id"))
.then { _ in
userSession
}
when(mock.remove(forClientId: "client_id")).thenDoNothing()
}
Expand All @@ -96,8 +93,8 @@ final class SharedKeychainSessionStorageFactoryTests: XCTestCase {

XCTAssertIdentical(keychain, sharedKeychainSessionStorageMock)
verify(sharedKeychainSessionStorageMock).checkEntitlements()
verify(sharedKeychainSessionStorageMock).store(any(), accessGroup: sharedAccessGroup, completion: anyClosure())
verify(keychainSessionStorageMock).get(forClientId: "client_id", completion: anyClosure())
verify(sharedKeychainSessionStorageMock).store(any(), accessGroup: sharedAccessGroup)
verify(keychainSessionStorageMock).get(forClientId: "client_id")
verify(keychainSessionStorageMock).remove(forClientId: "client_id")
}

Expand All @@ -108,35 +105,35 @@ final class SharedKeychainSessionStorageFactoryTests: XCTestCase {
when(mock.checkEntitlements()).then { _ in
return Data()
}
when(mock.store(any(), accessGroup: sharedAccessGroup, completion: anyClosure()))
.then { _, _, completion in
completion(.failure(KeychainStorageError.operationError))
when(mock.store(any(), accessGroup: sharedAccessGroup))
.then { _ in
throw KeychainStorageError.operationError
}
when(mock.getAll()).then { _ in
return []
}
}
let keychainSessionStorageMock = MockKeychainSessionStorage(service: "service_name", accessGroup: accessGroup)
stub(keychainSessionStorageMock) { mock in
when(mock.get(forClientId: "client_id", completion: anyClosure()))
.then { _, completion in
completion(userSession)
when(mock.get(forClientId: "client_id"))
.then { _ in
userSession
}
when(mock.remove(forClientId: "client_id")).thenDoNothing()
when(mock.store(any(), accessGroup: any(), completion: anyClosure()))
.then { _, _, completion in
completion(.success())
when(mock.store(any(), accessGroup: any()))
.then { _ in

}
}

let keychain = SharedKeychainSessionStorageFactory(keychain: keychainSessionStorageMock, sharedKeychain: sharedKeychainSessionStorageMock).makeKeychain(clientId: "client_id", service: "service_name", accessGroup: accessGroup, appIdentifierPrefix: "AZWSDFGHIJ")

XCTAssertIdentical(keychain, keychainSessionStorageMock)
verify(sharedKeychainSessionStorageMock).checkEntitlements()
verify(sharedKeychainSessionStorageMock).store(any(), accessGroup: sharedAccessGroup, completion: anyClosure())
verify(keychainSessionStorageMock).get(forClientId: "client_id", completion: anyClosure())
verify(sharedKeychainSessionStorageMock).store(any(), accessGroup: sharedAccessGroup)
verify(keychainSessionStorageMock).get(forClientId: "client_id")
verify(keychainSessionStorageMock).remove(forClientId: "client_id")
verify(keychainSessionStorageMock).store(any(), accessGroup: any(), completion: anyClosure())
verify(keychainSessionStorageMock).store(any(), accessGroup: any())
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ final class UserTests: XCTestCase {
}
let mockSessionStorage = MockSessionStorage()
stub(mockSessionStorage) { mock in
when(mock.store(any(), accessGroup: any(), completion: anyClosure())).then { _, _, completion in
completion(.success())
}
when(mock.store(any(), accessGroup: any())).then { _ in }
}

let client = Client(configuration: Fixtures.clientConfig, sessionStorage: mockSessionStorage, stateStorage: StateStorage(), httpClient: mockHTTPClient)
Expand All @@ -125,7 +123,7 @@ final class UserTests: XCTestCase {
verify(mockSessionStorage).store(ParameterMatcher<UserSession>{
$0.userTokens.accessToken == "newAccessToken" &&
$0.userTokens.refreshToken == "newRefreshToken"
}, accessGroup: any(), completion: anyClosure())
}, accessGroup: any())
default:
XCTFail("Unexpected result \(result)")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ class XCTestCaseWithMockHTTPClient: XCTestCase {

func stubSessionStorageStore(mockSessionStorage: MockSessionStorage, result: Result<Void, Error>) {
stub(mockSessionStorage) { mock in
when(mock.store(any(), accessGroup: any(), completion: anyClosure())).then { _, _, completion in
completion(result)
when(mock.store(any(), accessGroup: any())).then { _ in
result
}
}
}
Expand Down

0 comments on commit 7e38749

Please sign in to comment.