| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680 |
- // Copyright 2021 Google LLC
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- import Foundation
- @testable import FirebaseFunctions
- import FirebaseAuthInterop
- import FirebaseMessagingInterop
- import XCTest
- /// This file was intitialized as a direct port of `FirebaseFunctionsSwift/Tests/IntegrationTests.swift`
- /// which itself was ported from the Objective C `FirebaseFunctions/Tests/Integration/FIRIntegrationTests.m`
- ///
- /// The tests require the emulator to be running with `FirebaseFunctions/Backend/start.sh synchronous`
- /// The Firebase Functions called in the tests are implemented in `FirebaseFunctions/Backend/index.js`.
- struct DataTestRequest: Encodable {
- var bool: Bool
- var int: Int32
- var long: Int64
- var string: String
- var array: [Int32]
- // NOTE: Auto-synthesized Encodable conformance uses 'encodeIfPresent' to
- // encode Optional values. To encode Optional.none as null you either need
- // to write a manual encodable conformance or use a helper like the
- // propertyWrapper here:
- @NullEncodable var null: Bool?
- }
- @propertyWrapper
- struct NullEncodable<T>: Encodable where T: Encodable {
- var wrappedValue: T?
- init(wrappedValue: T?) {
- self.wrappedValue = wrappedValue
- }
- func encode(to encoder: Encoder) throws {
- var container = encoder.singleValueContainer()
- switch wrappedValue {
- case let .some(value): try container.encode(value)
- case .none: try container.encodeNil()
- }
- }
- }
- struct DataTestResponse: Decodable, Equatable {
- var message: String
- var long: Int64
- var code: Int32
- }
- class IntegrationTests: XCTestCase {
- let functions = Functions(projectID: "functions-integration-test",
- region: "us-central1",
- customDomain: nil,
- auth: nil,
- messaging: MessagingTokenProvider(),
- appCheck: nil)
- let projectID = "functions-swift-integration-test"
- override func setUp() {
- super.setUp()
- functions.useEmulator(withHost: "localhost", port: 5005)
- }
- func testData() {
- let expectation = expectation(description: #function)
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let function = functions.httpsCallable("dataTest",
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- function.call(data) { result in
- do {
- let response = try result.get()
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- } catch {
- XCTFail("Failed to unwrap the function result: \(error)")
- }
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testDataAsync() async throws {
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let function = functions.httpsCallable("dataTest",
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- let response = try await function.call(data)
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- }
- #endif
- func testScalar() {
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "scalarTest",
- requestAs: Int16.self,
- responseAs: Int.self
- )
- function.call(17) { result in
- do {
- let response = try result.get()
- XCTAssertEqual(response, 76)
- } catch {
- XCTAssert(false, "Failed to unwrap the function result: \(error)")
- }
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testScalarAsync() async throws {
- let function = functions.httpsCallable(
- "scalarTest",
- requestAs: Int16.self,
- responseAs: Int.self
- )
- let result = try await function.call(17)
- XCTAssertEqual(result, 76)
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testScalarAsyncAlternateSignature() async throws {
- let function: Callable<Int16, Int> = functions.httpsCallable("scalarTest")
- let result = try await function.call(17)
- XCTAssertEqual(result, 76)
- }
- #endif
- func testToken() {
- // Recreate functions with a token.
- let functions = Functions(
- projectID: "functions-integration-test",
- region: "us-central1",
- customDomain: nil,
- auth: AuthTokenProvider(token: "token"),
- messaging: MessagingTokenProvider(),
- appCheck: nil
- )
- functions.useEmulator(withHost: "localhost", port: 5005)
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "tokenTest",
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- XCTAssertNotNil(function)
- function.call([:]) { result in
- do {
- let data = try result.get()
- XCTAssertEqual(data, [:])
- } catch {
- XCTAssert(false, "Failed to unwrap the function result: \(error)")
- }
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testTokenAsync() async throws {
- // Recreate functions with a token.
- let functions = Functions(
- projectID: "functions-integration-test",
- region: "us-central1",
- customDomain: nil,
- auth: AuthTokenProvider(token: "token"),
- messaging: MessagingTokenProvider(),
- appCheck: nil
- )
- functions.useEmulator(withHost: "localhost", port: 5005)
- let function = functions.httpsCallable(
- "tokenTest",
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- let data = try await function.call([:])
- XCTAssertEqual(data, [:])
- }
- #endif
- func testFCMToken() {
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "FCMTokenTest",
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- function.call([:]) { result in
- do {
- let data = try result.get()
- XCTAssertEqual(data, [:])
- } catch {
- XCTAssert(false, "Failed to unwrap the function result: \(error)")
- }
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testFCMTokenAsync() async throws {
- let function = functions.httpsCallable(
- "FCMTokenTest",
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- let data = try await function.call([:])
- XCTAssertEqual(data, [:])
- }
- #endif
- func testNull() {
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "nullTest",
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- function.call(nil) { result in
- do {
- let data = try result.get()
- XCTAssertEqual(data, nil)
- } catch {
- XCTAssert(false, "Failed to unwrap the function result: \(error)")
- }
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testNullAsync() async throws {
- let function = functions.httpsCallable(
- "nullTest",
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- let data = try await function.call(nil)
- XCTAssertEqual(data, nil)
- }
- #endif
- func testMissingResult() {
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "missingResultTest",
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- function.call(nil) { result in
- do {
- _ = try result.get()
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.internal.rawValue, error.code)
- XCTAssertEqual("Response is missing data field.", error.localizedDescription)
- expectation.fulfill()
- return
- }
- XCTFail("Failed to throw error for missing result")
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testMissingResultAsync() async {
- let function = functions.httpsCallable(
- "missingResultTest",
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- do {
- _ = try await function.call(nil)
- XCTFail("Failed to throw error for missing result")
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.internal.rawValue, error.code)
- XCTAssertEqual("Response is missing data field.", error.localizedDescription)
- }
- }
- #endif
- func testUnhandledError() {
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "unhandledErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- function.call([]) { result in
- do {
- _ = try result.get()
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.internal.rawValue, error.code)
- XCTAssertEqual("INTERNAL", error.localizedDescription)
- expectation.fulfill()
- return
- }
- XCTFail("Failed to throw error for missing result")
- }
- XCTAssert(true)
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testUnhandledErrorAsync() async {
- let function = functions.httpsCallable(
- "unhandledErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- do {
- _ = try await function.call([])
- XCTFail("Failed to throw error for missing result")
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.internal.rawValue, error.code)
- XCTAssertEqual("INTERNAL", error.localizedDescription)
- }
- }
- #endif
- func testUnknownError() {
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "unknownErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- function.call([]) { result in
- do {
- _ = try result.get()
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.internal.rawValue, error.code)
- XCTAssertEqual("INTERNAL", error.localizedDescription)
- expectation.fulfill()
- return
- }
- XCTFail("Failed to throw error for missing result")
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testUnknownErrorAsync() async {
- let function = functions.httpsCallable(
- "unknownErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- do {
- _ = try await function.call([])
- XCTAssertFalse(true, "Failed to throw error for missing result")
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.internal.rawValue, error.code)
- XCTAssertEqual("INTERNAL", error.localizedDescription)
- }
- }
- #endif
- func testExplicitError() {
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "explicitErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- function.call([]) { result in
- do {
- _ = try result.get()
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.outOfRange.rawValue, error.code)
- XCTAssertEqual("explicit nope", error.localizedDescription)
- XCTAssertEqual(["start": 10 as Int32, "end": 20 as Int32, "long": 30],
- error.userInfo["details"] as! [String: Int32])
- expectation.fulfill()
- return
- }
- XCTFail("Failed to throw error for missing result")
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testExplicitErrorAsync() async {
- let function = functions.httpsCallable(
- "explicitErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- do {
- _ = try await function.call([])
- XCTAssertFalse(true, "Failed to throw error for missing result")
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.outOfRange.rawValue, error.code)
- XCTAssertEqual("explicit nope", error.localizedDescription)
- XCTAssertEqual(["start": 10 as Int32, "end": 20 as Int32, "long": 30],
- error.userInfo["details"] as! [String: Int32])
- }
- }
- #endif
- func testHttpError() {
- let expectation = expectation(description: #function)
- let function = functions.httpsCallable(
- "httpErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- XCTAssertNotNil(function)
- function.call([]) { result in
- do {
- _ = try result.get()
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.invalidArgument.rawValue, error.code)
- expectation.fulfill()
- return
- }
- XCTFail("Failed to throw error for missing result")
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testHttpErrorAsync() async {
- let function = functions.httpsCallable(
- "httpErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- do {
- _ = try await function.call([])
- XCTAssertFalse(true, "Failed to throw error for missing result")
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.invalidArgument.rawValue, error.code)
- }
- }
- #endif
- func testTimeout() {
- let expectation = expectation(description: #function)
- var function = functions.httpsCallable(
- "timeoutTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- function.timeoutInterval = 0.05
- function.call([]) { result in
- do {
- _ = try result.get()
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.deadlineExceeded.rawValue, error.code)
- XCTAssertEqual("DEADLINE EXCEEDED", error.localizedDescription)
- XCTAssertNil(error.userInfo["details"])
- expectation.fulfill()
- return
- }
- XCTFail("Failed to throw error for missing result")
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testTimeoutAsync() async {
- var function = functions.httpsCallable(
- "timeoutTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- function.timeoutInterval = 0.05
- do {
- _ = try await function.call([])
- XCTAssertFalse(true, "Failed to throw error for missing result")
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.deadlineExceeded.rawValue, error.code)
- XCTAssertEqual("DEADLINE EXCEEDED", error.localizedDescription)
- XCTAssertNil(error.userInfo["details"])
- }
- }
- #endif
- func testCallAsFunction() {
- let expectation = expectation(description: #function)
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let function = functions.httpsCallable("dataTest",
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- function(data) { result in
- do {
- let response = try result.get()
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- expectation.fulfill()
- } catch {
- XCTAssert(false, "Failed to unwrap the function result: \(error)")
- }
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testCallAsFunctionAsync() async throws {
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let function = functions.httpsCallable("dataTest",
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- let response = try await function(data)
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- }
- #endif
- func testInferredTypes() {
- let expectation = expectation(description: #function)
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let function: Callable<DataTestRequest, DataTestResponse> = functions.httpsCallable("dataTest")
- function(data) { result in
- do {
- let response = try result.get()
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- expectation.fulfill()
- } catch {
- XCTAssert(false, "Failed to unwrap the function result: \(error)")
- }
- }
- waitForExpectations(timeout: 5)
- }
- #if compiler(>=5.5.2) && canImport(_Concurrency)
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testInferredTyesAsync() async throws {
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let function: Callable<DataTestRequest, DataTestResponse> = functions
- .httpsCallable("dataTest")
- let response = try await function(data)
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- }
- #endif
- }
- private class AuthTokenProvider: AuthInterop {
- func getUserID() -> String? {
- return "fake user"
- }
- let token: String
- init(token: String) {
- self.token = token
- }
- func getToken(forcingRefresh: Bool, completion: (String?, Error?) -> Void) {
- completion(token, nil)
- }
- }
- private class MessagingTokenProvider: NSObject, MessagingInterop {
- var fcmToken: String? { return "fakeFCMToken" }
- }
|