GameCenterAuthProviderTests.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. import Combine
  16. import GameKit
  17. import XCTest
  18. import FirebaseAuth
  19. class GameCenterAuthProviderTests: XCTestCase {
  20. override class func setUp() {
  21. FirebaseApp.configureForTests()
  22. GKLocalPlayer.mock(with: MockLocalPlayer.self)
  23. }
  24. override class func tearDown() {
  25. FirebaseApp.app()?.delete { success in
  26. if success {
  27. print("Shut down app successfully.")
  28. } else {
  29. print("💥 There was a problem when shutting down the app..")
  30. }
  31. }
  32. }
  33. fileprivate static let playerID = "PLAYERID"
  34. fileprivate static let displayName = "DISPLAYNAME"
  35. fileprivate static let publicKeyURL = "PUBLICKEYURL"
  36. fileprivate static let signature = "AAAABBBBCCCC"
  37. fileprivate static let salt = "AAAA"
  38. fileprivate static let timestamp: UInt64 = 12_345_678
  39. class MockLocalPlayer: GKLocalPlayer {
  40. static var _local: MockLocalPlayer!
  41. override class var local: GKLocalPlayer { _local }
  42. override var playerID: String { GameCenterAuthProviderTests.playerID }
  43. override var alias: String { GameCenterAuthProviderTests.displayName }
  44. override var displayName: String { GameCenterAuthProviderTests.displayName }
  45. var _isAuthenticated: Bool = true
  46. override var isAuthenticated: Bool { _isAuthenticated }
  47. var _errorIdentityVerificationSignature: NSError?
  48. override func generateIdentityVerificationSignature(completionHandler: ((URL?, Data?, Data?,
  49. UInt64,
  50. Error?) -> Void)? =
  51. nil) {
  52. let url = URL(string: GameCenterAuthProviderTests.publicKeyURL)
  53. let signature = Data(base64Encoded: GameCenterAuthProviderTests.signature)
  54. let salt = Data(base64Encoded: GameCenterAuthProviderTests.salt)
  55. let timestamp = GameCenterAuthProviderTests.timestamp
  56. if _errorIdentityVerificationSignature != nil {
  57. completionHandler?(nil, nil, nil, 0, _errorIdentityVerificationSignature)
  58. } else {
  59. completionHandler?(url, signature, salt, timestamp, nil)
  60. }
  61. }
  62. }
  63. class MockAuthBackend: AuthBackendImplementationMock {}
  64. func testGetCredentialWithLocalPlayer() {
  65. // given
  66. FIRAuthBackend.setBackendImplementation(MockAuthBackend())
  67. MockLocalPlayer._local = MockLocalPlayer()
  68. var cancellables = Set<AnyCancellable>()
  69. let getCredentialExpectation = expectation(description: "Get credential")
  70. // when
  71. GameCenterAuthProvider.getCredential()
  72. .sink { completion in
  73. switch completion {
  74. case .finished:
  75. print("Finished")
  76. case let .failure(error):
  77. XCTFail("💥 Something went wrong: \(error)")
  78. }
  79. } receiveValue: { credential in
  80. do {
  81. XCTAssertTrue(Thread.isMainThread)
  82. let gameCenterCredential =
  83. try XCTUnwrap(credential as? FIRGameCenterAuthCredential)
  84. XCTAssertEqual(gameCenterCredential.displayName, Self.displayName)
  85. XCTAssertEqual(gameCenterCredential.playerID, Self.playerID)
  86. XCTAssertEqual(
  87. gameCenterCredential.publicKeyURL.absoluteString,
  88. Self.publicKeyURL
  89. )
  90. XCTAssertEqual(gameCenterCredential.timestamp, Self.timestamp)
  91. XCTAssertEqual(gameCenterCredential.salt.base64EncodedString(), Self.salt)
  92. XCTAssertEqual(
  93. gameCenterCredential.signature.base64EncodedString(),
  94. Self.signature
  95. )
  96. } catch {
  97. XCTFail("💥 Expect non-nil OAuth credential: \(error)")
  98. }
  99. getCredentialExpectation.fulfill()
  100. }
  101. .store(in: &cancellables)
  102. // then
  103. wait(for: [getCredentialExpectation], timeout: expectationTimeout)
  104. }
  105. func testGetCredentialPlayerNotAuthenticatedWithLocalPlayer() {
  106. // given
  107. FIRAuthBackend.setBackendImplementation(MockAuthBackend())
  108. MockLocalPlayer._local._isAuthenticated = false
  109. var cancellables = Set<AnyCancellable>()
  110. let getCredentialExpectation = expectation(description: "Get credential")
  111. // when
  112. GameCenterAuthProvider.getCredential()
  113. .sink { completion in
  114. if case let .failure(error as NSError) = completion {
  115. XCTAssertEqual(error.code, AuthErrorCode.localPlayerNotAuthenticated.rawValue)
  116. getCredentialExpectation.fulfill()
  117. }
  118. } receiveValue: { authDataResult in
  119. XCTFail("💥 result unexpected")
  120. }
  121. .store(in: &cancellables)
  122. // then
  123. wait(for: [getCredentialExpectation], timeout: expectationTimeout)
  124. }
  125. func testGetCredentialInvalidPlayerWithLocalPlayer() {
  126. // given
  127. FIRAuthBackend.setBackendImplementation(MockAuthBackend())
  128. MockLocalPlayer._local = MockLocalPlayer()
  129. MockLocalPlayer._local
  130. ._errorIdentityVerificationSignature = GKError(.invalidPlayer) as NSError
  131. var cancellables = Set<AnyCancellable>()
  132. let getCredentialExpectation = expectation(description: "Get credential")
  133. // when
  134. GameCenterAuthProvider.getCredential()
  135. .sink { completion in
  136. if case let .failure(error as NSError) = completion {
  137. XCTAssertEqual(error.code, GKError.invalidPlayer.rawValue)
  138. getCredentialExpectation.fulfill()
  139. }
  140. } receiveValue: { authDataResult in
  141. XCTFail("💥 result unexpected")
  142. }
  143. .store(in: &cancellables)
  144. // then
  145. wait(for: [getCredentialExpectation], timeout: expectationTimeout)
  146. }
  147. }