FacebookTests.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. /*
  2. * Copyright 2020 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import FirebaseAuth
  18. import GTMSessionFetcher
  19. import XCTest
  20. class FacebookTests: TestsBase {
  21. func testSignInWithFacebook() {
  22. let auth = Auth.auth()
  23. let userInfoDict = self.createFacebookTestingAccount()
  24. guard let facebookAccessToken = userInfoDict["access_token"] as! String? else {
  25. XCTAssertTrue(false, "Failed to get facebookAccessToken")
  26. return
  27. }
  28. guard let facebookAccountID = userInfoDict["id"] as! String? else {
  29. XCTAssertTrue(false, "Failed to get facebookAccountID")
  30. return
  31. }
  32. let credential = FacebookAuthProvider.credential(withAccessToken: facebookAccessToken)
  33. let expectation = self.expectation(description: "Signing in with Facebook finished.")
  34. auth.signIn(with: credential) { (result, error) in
  35. if let error = error {
  36. XCTAssertTrue(false, "Signing in with Facebook had error: \(error)")
  37. } else {
  38. XCTAssertEqual(auth.currentUser?.displayName, Credentials.kFacebookUserName)
  39. }
  40. expectation.fulfill()
  41. }
  42. waitForExpectations(timeout:TestsBase.kExpectationsTimeout)
  43. // Clean up the created Firebase/Facebook user for future runs.
  44. self.deleteCurrentUser()
  45. self.deleteFacebookTestingAccountbyID(facebookAccountID)
  46. }
  47. func testLinkAnonymousAccountToFacebookAccount() {
  48. let auth = Auth.auth()
  49. self.signInAnonymously()
  50. let userInfoDict = self.createFacebookTestingAccount()
  51. guard let facebookAccessToken = userInfoDict["access_token"] as! String? else {
  52. XCTAssertTrue(false, "Failed to get facebookAccessToken")
  53. return
  54. }
  55. guard let facebookAccountID = userInfoDict["id"] as! String? else {
  56. XCTAssertTrue(false, "Failed to get facebookAccountID")
  57. return
  58. }
  59. let credential = FacebookAuthProvider.credential(withAccessToken: facebookAccessToken)
  60. let expectation = self.expectation(description: "Facebook linking finished.")
  61. auth.currentUser?.link(with: credential, completion: { (result, error) in
  62. if let error = error {
  63. XCTAssertTrue(false, "Link to Firebase error: \(error)")
  64. } else {
  65. guard let providers = (auth.currentUser?.providerData) else {
  66. XCTAssertTrue(false, "Failed to get providers")
  67. return
  68. }
  69. XCTAssertEqual(providers.count, 1)
  70. XCTAssertEqual(providers[0].providerID, "facebook.com")
  71. }
  72. expectation.fulfill()
  73. })
  74. waitForExpectations(timeout:TestsBase.kExpectationsTimeout)
  75. // Clean up the created Firebase/Facebook user for future runs.
  76. self.deleteCurrentUser()
  77. self.deleteFacebookTestingAccountbyID(facebookAccountID)
  78. }
  79. ///** Creates a Facebook testing account using Facebook Graph API and return a dictionary that
  80. // * constains "id", "access_token", "login_url", "email" and "password" of the created account.
  81. // */
  82. func createFacebookTestingAccount() -> Dictionary<String, Any> {
  83. var returnValue : Dictionary<String, Any> = [:]
  84. let urltoCreateTestUser = "https://graph.facebook.com/\(Credentials.kFacebookAppID)" +
  85. "/accounts/test-users"
  86. let bodyString = "installed=true&name=\(Credentials.kFacebookUserName)" +
  87. "&permissions=read_stream&access_token=\(Credentials.kFacebookAppAccessToken)"
  88. let postData = bodyString.data(using: .utf8)
  89. let service = GTMSessionFetcherService.init()
  90. let fetcher = service.fetcher(withURLString: urltoCreateTestUser)
  91. fetcher.bodyData = postData
  92. fetcher.setRequestValue("text/plain", forHTTPHeaderField: "Content-Type")
  93. let expectation = self.expectation(description: "Creating Facebook account finished.")
  94. fetcher.beginFetch { (data, error) in
  95. if let error = error {
  96. let error = error as NSError
  97. if let message = String.init(data: error.userInfo["data"] as! Data, encoding: .utf8) {
  98. // May get transient errors here for too many api calls when tests run frequently.
  99. XCTAssertTrue(false, "Creating Facebook account failed with error: \(message)")
  100. } else {
  101. XCTAssertTrue(false, "Creating Facebook account failed with error: \(error)")
  102. }
  103. } else {
  104. do {
  105. let data = try XCTUnwrap(data)
  106. guard let userInfo = String.init(data: data, encoding: .utf8) else {
  107. XCTAssertTrue(false, "Failed to convert data to string")
  108. return
  109. }
  110. print("The created Facebook testing account info is: \(String(describing: userInfo))")
  111. returnValue = try JSONSerialization.jsonObject(with: data, options: [])
  112. as! Dictionary<String, Any>
  113. } catch (let error) {
  114. XCTAssertTrue(false, "Failed to unwrap data \(error)")
  115. }
  116. }
  117. expectation.fulfill()
  118. }
  119. waitForExpectations(timeout:TestsBase.kExpectationsTimeout)
  120. return returnValue
  121. }
  122. //** Delete a Facebook testing account by account Id using Facebook Graph API. */
  123. func deleteFacebookTestingAccountbyID(_ accountID: String) {
  124. let urltoDeleteTestUser = "https://graph.facebook.com/\(accountID)"
  125. let bodyString = "method=delete&access_token=\(Credentials.kFacebookAppAccessToken)"
  126. let postData = bodyString.data(using: .utf8)
  127. let service = GTMSessionFetcherService.init()
  128. let fetcher = service.fetcher(withURLString: urltoDeleteTestUser)
  129. fetcher.bodyData = postData
  130. fetcher.setRequestValue("text/plain", forHTTPHeaderField: "Content-Type")
  131. let expectation = self.expectation(description: "Deleting Facebook account finished.")
  132. fetcher.beginFetch { (data, error) in
  133. if let error = error {
  134. XCTAssertTrue(false, "Deleting Facebook account failed with error: \(error)")
  135. }
  136. expectation.fulfill()
  137. }
  138. waitForExpectations(timeout:TestsBase.kExpectationsTimeout)
  139. }
  140. }