| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343 |
- // 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
- import FirebaseAuthInterop
- @testable import FirebaseFunctions
- import FirebaseMessagingInterop
- import XCTest
- /// This file was initialized 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
- }
- /// - Important: These tests require the emulator. Run `./FirebaseFunctions/Backend/start.sh`
- class IntegrationTests: XCTestCase {
- let functions = Functions(projectID: "functions-integration-test",
- region: "us-central1",
- customDomain: nil,
- auth: nil,
- messaging: MessagingTokenProvider(),
- appCheck: nil)
- override func setUp() {
- super.setUp()
- functions.useEmulator(withHost: "localhost", port: 5005)
- }
- func emulatorURL(_ funcName: String) -> URL {
- return URL(string: "http://localhost:5005/functions-integration-test/us-central1/\(funcName)")!
- }
- func testData() {
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let byName = functions.httpsCallable("dataTest",
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- let byURL = functions.httpsCallable(emulatorURL("dataTest"),
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @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 byName = functions.httpsCallable("dataTest",
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- let byUrl = functions.httpsCallable(emulatorURL("dataTest"),
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- for function in [byName, byUrl] {
- let response = try await function.call(data)
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- }
- }
- func testScalar() {
- let byName = functions.httpsCallable(
- "scalarTest",
- requestAs: Int16.self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("scalarTest"),
- requestAs: Int16.self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testScalarAsync() async throws {
- let byName = functions.httpsCallable(
- "scalarTest",
- requestAs: Int16.self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("scalarTest"),
- requestAs: Int16.self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- 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 byName: Callable<Int16, Int> = functions.httpsCallable("scalarTest")
- let byURL: Callable<Int16, Int> = functions.httpsCallable(emulatorURL("scalarTest"))
- for function in [byName, byURL] {
- let result = try await function.call(17)
- XCTAssertEqual(result, 76)
- }
- }
- 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 byName = functions.httpsCallable(
- "tokenTest",
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("tokenTest"),
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @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 byName = functions.httpsCallable(
- "tokenTest",
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("tokenTest"),
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- for function in [byName, byURL] {
- let data = try await function.call([:])
- XCTAssertEqual(data, [:])
- }
- }
- func testFCMToken() {
- let byName = functions.httpsCallable(
- "FCMTokenTest",
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("FCMTokenTest"),
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #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)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testFCMTokenAsync() async throws {
- let byName = functions.httpsCallable(
- "FCMTokenTest",
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("FCMTokenTest"),
- requestAs: [String: Int].self,
- responseAs: [String: Int].self
- )
- for function in [byName, byURL] {
- let data = try await function.call([:])
- XCTAssertEqual(data, [:])
- }
- }
- func testNull() {
- let byName = functions.httpsCallable(
- "nullTest",
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("nullTest"),
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testNullAsync() async throws {
- let byName = functions.httpsCallable(
- "nullTest",
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("nullTest"),
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- for function in [byName, byURL] {
- let data = try await function.call(nil)
- XCTAssertEqual(data, nil)
- }
- }
- func testMissingResult() {
- let byName = functions.httpsCallable(
- "missingResultTest",
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("missingResultTest"),
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testMissingResultAsync() async {
- let byName = functions.httpsCallable(
- "missingResultTest",
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("missingResultTest"),
- requestAs: Int?.self,
- responseAs: Int?.self
- )
- for function in [byName, byURL] {
- 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)
- }
- }
- }
- func testUnhandledError() {
- let byName = functions.httpsCallable(
- "unhandledErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("unhandledErrorTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testUnhandledErrorAsync() async {
- let byName = functions.httpsCallable(
- "unhandledErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- "unhandledErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- 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)
- }
- }
- }
- func testUnknownError() {
- let byName = functions.httpsCallable(
- "unknownErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("unknownErrorTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testUnknownErrorAsync() async {
- let byName = functions.httpsCallable(
- "unknownErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("unknownErrorTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- 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)
- }
- }
- }
- func testExplicitError() {
- let byName = functions.httpsCallable(
- "explicitErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- "explicitErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testExplicitErrorAsync() async {
- let byName = functions.httpsCallable(
- "explicitErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("explicitErrorTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- 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])
- }
- }
- }
- func testHttpError() {
- let byName = functions.httpsCallable(
- "httpErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("httpErrorTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testHttpErrorAsync() async {
- let byName = functions.httpsCallable(
- "httpErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("httpErrorTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- 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)
- }
- }
- }
- func testThrowError() {
- let byName = functions.httpsCallable(
- "throwTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("throwTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- XCTAssertNotNil(function)
- function.call([]) { result in
- do {
- _ = try result.get()
- } catch {
- let error = error as NSError
- XCTAssertEqual(FunctionsErrorCode.invalidArgument.rawValue, error.code)
- XCTAssertEqual(error.localizedDescription, "Invalid test requested.")
- expectation.fulfill()
- return
- }
- XCTFail("Failed to throw error for missing result")
- }
- waitForExpectations(timeout: 5)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testThrowErrorAsync() async {
- let byName = functions.httpsCallable(
- "throwTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("throwTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for function in [byName, byURL] {
- 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)
- XCTAssertEqual(error.localizedDescription, "Invalid test requested.")
- }
- }
- }
- func testTimeout() {
- let byName = functions.httpsCallable(
- "timeoutTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- let byURL = functions.httpsCallable(
- emulatorURL("timeoutTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- for var function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- func testTimeoutAsync() async {
- var byName = functions.httpsCallable(
- "timeoutTest",
- requestAs: [Int].self,
- responseAs: Int.self
- )
- byName.timeoutInterval = 0.05
- var byURL = functions.httpsCallable(
- emulatorURL("timeoutTest"),
- requestAs: [Int].self,
- responseAs: Int.self
- )
- byURL.timeoutInterval = 0.05
- for function in [byName, byURL] {
- 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"])
- }
- }
- }
- func testCallAsFunction() {
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let byName = functions.httpsCallable("dataTest",
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- let byURL = functions.httpsCallable(emulatorURL("dataTest"),
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @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 byName = functions.httpsCallable("dataTest",
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- let byURL = functions.httpsCallable(emulatorURL("dataTest"),
- requestAs: DataTestRequest.self,
- responseAs: DataTestResponse.self)
- for function in [byName, byURL] {
- let response = try await function(data)
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- }
- }
- func testInferredTypes() {
- let data = DataTestRequest(
- bool: true,
- int: 2,
- long: 9_876_543_210,
- string: "four",
- array: [5, 6],
- null: nil
- )
- let byName: Callable<DataTestRequest, DataTestResponse> = functions.httpsCallable("dataTest")
- let byURL: Callable<DataTestRequest, DataTestResponse> = functions
- .httpsCallable(emulatorURL("dataTest"))
- for function in [byName, byURL] {
- let expectation = expectation(description: #function)
- 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)
- }
- }
- @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 byName: Callable<DataTestRequest, DataTestResponse> = functions
- .httpsCallable("dataTest")
- let byURL: Callable<DataTestRequest, DataTestResponse> = functions
- .httpsCallable(emulatorURL("dataTest"))
- for function in [byName, byURL] {
- let response = try await function(data)
- let expected = DataTestResponse(
- message: "stub response",
- long: 420,
- code: 42
- )
- XCTAssertEqual(response, expected)
- }
- }
- func testFunctionsReturnsOnMainThread() {
- let expectation = expectation(description: #function)
- functions.httpsCallable(
- "scalarTest",
- requestAs: Int16.self,
- responseAs: Int.self
- ).call(17) { result in
- guard case .success = result else {
- return XCTFail("Unexpected failure.")
- }
- XCTAssert(Thread.isMainThread)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- func testFunctionsThrowsOnMainThread() {
- let expectation = expectation(description: #function)
- functions.httpsCallable(
- "httpErrorTest",
- requestAs: [Int].self,
- responseAs: Int.self
- ).call([]) { result in
- guard case .failure = result else {
- return XCTFail("Unexpected failure.")
- }
- XCTAssert(Thread.isMainThread)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- }
- // MARK: - Streaming
- /// A convenience type used to represent that a callable function does not
- /// accept parameters.
- ///
- /// This can be used as the generic `Request` parameter to ``Callable`` to
- /// indicate the callable function does not accept parameters.
- private struct EmptyRequest: Encodable {}
- @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
- extension IntegrationTests {
- func testStream_NoArgs() async throws {
- // 1. Custom `EmptyRequest` struct is passed as a placeholder generic arg.
- let callable: Callable<EmptyRequest, String> = functions.httpsCallable("genStream")
- // 2. No request data is passed when creating stream.
- let stream = try callable.stream()
- var streamContents: [String] = []
- for try await response in stream {
- streamContents.append(response)
- }
- XCTAssertEqual(
- streamContents,
- ["hello", "world", "this", "is", "cool"]
- )
- }
- @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *)
- func testStream_NoArgs_UeeNever() async throws {
- let callable: Callable<Never, String> = functions.httpsCallable("genStream")
- let stream = try callable.stream()
- var streamContents: [String] = []
- for try await response in stream {
- streamContents.append(response)
- }
- XCTAssertEqual(
- streamContents,
- ["hello", "world", "this", "is", "cool"]
- )
- }
- func testStream_SimpleStreamResponse() async throws {
- let callable: Callable<EmptyRequest, StreamResponse<String, String>> = functions
- .httpsCallable("genStream")
- let stream = try callable.stream()
- var streamContents: [String] = []
- for try await response in stream {
- switch response {
- case let .message(message):
- streamContents.append(message)
- case let .result(result):
- streamContents.append(result)
- }
- }
- XCTAssertEqual(
- streamContents,
- ["hello", "world", "this", "is", "cool", "hello world this is cool"]
- )
- }
- func testStream_CodableString() async throws {
- let byName: Callable<EmptyRequest, String> = functions.httpsCallable("genStream")
- let stream = try byName.stream()
- let result: [String] = try await stream.reduce([]) { $0 + [$1] }
- XCTAssertEqual(result, ["hello", "world", "this", "is", "cool"])
- }
- private struct Location: Codable, Equatable {
- let name: String
- }
- private struct WeatherForecast: Decodable, Equatable {
- enum Conditions: String, Decodable {
- case sunny
- case rainy
- case snowy
- }
- let location: Location
- let temperature: Int
- let conditions: Conditions
- }
- private struct WeatherForecastReport: Decodable, Equatable {
- let forecasts: [WeatherForecast]
- }
- func testStream_CodableObject() async throws {
- let callable: Callable<[Location], WeatherForecast> = functions
- .httpsCallable("genStreamWeather")
- let stream = try callable.stream([
- Location(name: "Toronto"),
- Location(name: "London"),
- Location(name: "Dubai"),
- ])
- let result: [WeatherForecast] = try await stream.reduce([]) { $0 + [$1] }
- XCTAssertEqual(
- result,
- [
- WeatherForecast(location: Location(name: "Toronto"), temperature: 25, conditions: .snowy),
- WeatherForecast(location: Location(name: "London"), temperature: 50, conditions: .rainy),
- WeatherForecast(location: Location(name: "Dubai"), temperature: 75, conditions: .sunny),
- ]
- )
- }
- func testStream_ResponseMessageDecodingFailure() async throws {
- let callable: Callable<[Location], StreamResponse<WeatherForecast, WeatherForecastReport>> =
- functions
- .httpsCallable("genStreamWeatherError")
- let stream = try callable.stream([Location(name: "Toronto")])
- do {
- for try await _ in stream {
- XCTFail("Expected error to be thrown from stream.")
- }
- } catch let error as FunctionsError where error.code == .dataLoss {
- XCTAssertNotNil(error.errorUserInfo[NSUnderlyingErrorKey] as? DecodingError)
- }
- }
- func testStream_ResponseResultDecodingFailure() async throws {
- let callable: Callable<[Location], StreamResponse<WeatherForecast, String>> = functions
- .httpsCallable("genStreamWeather")
- let stream = try callable.stream([Location(name: "Toronto")])
- do {
- for try await response in stream {
- if case .result = response {
- XCTFail("Expected error to be thrown from stream.")
- }
- }
- } catch let error as FunctionsError where error.code == .dataLoss {
- XCTAssertNotNil(error.errorUserInfo[NSUnderlyingErrorKey] as? DecodingError)
- }
- }
- func testStream_ComplexStreamResponse() async throws {
- let callable: Callable<[Location], StreamResponse<WeatherForecast, WeatherForecastReport>> =
- functions
- .httpsCallable("genStreamWeather")
- let stream = try callable.stream([
- Location(name: "Toronto"),
- Location(name: "London"),
- Location(name: "Dubai"),
- ])
- var streamContents: [WeatherForecast] = []
- var streamResult: WeatherForecastReport?
- for try await response in stream {
- switch response {
- case let .message(message):
- streamContents.append(message)
- case let .result(result):
- streamResult = result
- }
- }
- XCTAssertEqual(
- streamContents,
- [
- WeatherForecast(location: Location(name: "Toronto"), temperature: 25, conditions: .snowy),
- WeatherForecast(location: Location(name: "London"), temperature: 50, conditions: .rainy),
- WeatherForecast(location: Location(name: "Dubai"), temperature: 75, conditions: .sunny),
- ]
- )
- try XCTAssertEqual(
- XCTUnwrap(streamResult), WeatherForecastReport(forecasts: streamContents)
- )
- }
- func testStream_ComplexStreamResponse_Functional() async throws {
- let callable: Callable<[Location], StreamResponse<WeatherForecast, WeatherForecastReport>> =
- functions
- .httpsCallable("genStreamWeather")
- let stream = try callable.stream([
- Location(name: "Toronto"),
- Location(name: "London"),
- Location(name: "Dubai"),
- ])
- let result: (accumulatedMessages: [WeatherForecast], result: WeatherForecastReport?) =
- try await stream.reduce(([], nil)) { partialResult, streamResponse in
- switch streamResponse {
- case let .message(message):
- (partialResult.accumulatedMessages + [message], partialResult.result)
- case let .result(result):
- (partialResult.accumulatedMessages, result)
- }
- }
- XCTAssertEqual(
- result.accumulatedMessages,
- [
- WeatherForecast(location: Location(name: "Toronto"), temperature: 25, conditions: .snowy),
- WeatherForecast(location: Location(name: "London"), temperature: 50, conditions: .rainy),
- WeatherForecast(location: Location(name: "Dubai"), temperature: 75, conditions: .sunny),
- ]
- )
- try XCTAssertEqual(
- XCTUnwrap(result.result), WeatherForecastReport(forecasts: result.accumulatedMessages)
- )
- }
- func testStream_Canceled() async throws {
- let task = Task.detached { [self] in
- let callable: Callable<EmptyRequest, String> = functions.httpsCallable("genStream")
- let stream = try callable.stream()
- // Since we cancel the call we are expecting an empty array.
- return try await stream.reduce([]) { $0 + [$1] } as [String]
- }
- // We cancel the task and we expect a null response even if the stream was initiated.
- task.cancel()
- let respone = try await task.value
- XCTAssertEqual(respone, [])
- }
- func testStream_NonexistentFunction() async throws {
- let callable: Callable<EmptyRequest, String> = functions.httpsCallable(
- "nonexistentFunction"
- )
- let stream = try callable.stream()
- do {
- for try await _ in stream {
- XCTFail("Expected error to be thrown from stream.")
- }
- } catch let error as FunctionsError where error.code == .notFound {
- XCTAssertEqual(error.localizedDescription, "NOT FOUND")
- }
- }
- func testStream_StreamError() async throws {
- let callable: Callable<EmptyRequest, String> = functions.httpsCallable("genStreamError")
- let stream = try callable.stream()
- do {
- for try await _ in stream {
- XCTFail("Expected error to be thrown from stream.")
- }
- } catch let error as FunctionsError where error.code == .internal {
- XCTAssertEqual(error.localizedDescription, "INTERNAL")
- }
- }
- func testStream_RequestEncodingFailure() async throws {
- struct Foo: Encodable {
- enum CodingKeys: CodingKey {}
- func encode(to encoder: any Encoder) throws {
- throw EncodingError
- .invalidValue("", EncodingError.Context(codingPath: [], debugDescription: ""))
- }
- }
- let callable: Callable<Foo, String> = functions
- .httpsCallable("genStream")
- do {
- _ = try callable.stream(Foo())
- } catch let error as FunctionsError where error.code == .invalidArgument {
- _ = try XCTUnwrap(error.errorUserInfo[NSUnderlyingErrorKey] as? EncodingError)
- }
- }
- /// This tests an edge case to assert that if a custom `Response` is used
- /// that matches the decoding logic of `StreamResponse`, the custom
- /// `Response` does not decode successfully.
- func testStream_ResultIsOnlyExposedInStreamResponse() async throws {
- // The implementation is copied from `StreamResponse`. The only difference is the do-catch is
- // removed from the decoding initializer.
- enum MyStreamResponse<Message: Decodable, Result: Decodable>: Decodable {
- /// The message yielded by the callable function.
- case message(Message)
- /// The final result returned by the callable function.
- case result(Result)
- private enum CodingKeys: String, CodingKey {
- case message
- case result
- }
- public init(from decoder: any Decoder) throws {
- let container = try decoder
- .container(keyedBy: Self<Message, Result>.CodingKeys.self)
- var allKeys = ArraySlice(container.allKeys)
- guard let onlyKey = allKeys.popFirst(), allKeys.isEmpty else {
- throw DecodingError
- .typeMismatch(
- Self<Message,
- Result>.self,
- DecodingError.Context(
- codingPath: container.codingPath,
- debugDescription: "Invalid number of keys found, expected one.",
- underlyingError: nil
- )
- )
- }
- switch onlyKey {
- case .message:
- self = try Self
- .message(container.decode(Message.self, forKey: .message))
- case .result:
- self = try Self
- .result(container.decode(Result.self, forKey: .result))
- }
- }
- }
- let callable: Callable<[Location], MyStreamResponse<WeatherForecast, WeatherForecastReport>> =
- functions
- .httpsCallable("genStreamWeather")
- let stream = try callable.stream([Location(name: "Toronto")])
- do {
- for try await _ in stream {
- XCTFail("Expected error to be thrown from stream.")
- }
- } catch let error as FunctionsError where error.code == .dataLoss {
- XCTAssertNotNil(error.errorUserInfo[NSUnderlyingErrorKey] as? DecodingError)
- }
- }
- func testStream_ForNonStreamingCF3() async throws {
- let callable: Callable<Int16, Int> = functions.httpsCallable("scalarTest")
- let stream = try callable.stream(17)
- do {
- for try await _ in stream {
- XCTFail("Expected error to be thrown from stream.")
- }
- } catch let error as FunctionsError where error.code == .dataLoss {
- XCTAssertEqual(error.localizedDescription, "Unexpected format for streamed response.")
- }
- }
- func testStream_EmptyStream() async throws {
- let callable: Callable<EmptyRequest, String> = functions.httpsCallable("genStreamEmpty")
- var streamContents: [String] = []
- for try await response in try callable.stream() {
- streamContents.append(response)
- }
- XCTAssertEqual(streamContents, [])
- }
- func testStream_ResultOnly() async throws {
- let callable: Callable<EmptyRequest, String> = functions.httpsCallable("genStreamResultOnly")
- let stream = try callable.stream()
- for try await _ in stream {
- // The stream should not yield anything, so this should not be reached.
- XCTFail("Stream should not yield any messages")
- }
- // Because StreamResponse was not used, the result is not accessible,
- // but the message should not throw.
- }
- func testStream_ResultOnly_StreamResponse() async throws {
- struct EmptyResponse: Decodable {}
- let callable: Callable<EmptyRequest, StreamResponse<EmptyResponse, String>> = functions
- .httpsCallable(
- "genStreamResultOnly"
- )
- let stream = try callable.stream()
- var streamResult = ""
- for try await response in stream {
- switch response {
- case .message:
- XCTFail("Stream should not yield any messages")
- case let .result(result):
- streamResult = result
- }
- }
- // The hardcoded string matches the CF3's return value.
- XCTAssertEqual(streamResult, "Only a result")
- }
- func testStream_UnexpectedType() async throws {
- // This function yields strings, not integers.
- let callable: Callable<EmptyRequest, Int> = functions.httpsCallable("genStream")
- let stream = try callable.stream()
- do {
- for try await _ in stream {
- XCTFail("Expected error to be thrown from stream.")
- }
- } catch let error as FunctionsError where error.code == .dataLoss {
- XCTAssertNotNil(error.errorUserInfo[NSUnderlyingErrorKey] as? DecodingError)
- }
- }
- func testStream_Timeout() async throws {
- var callable: Callable<EmptyRequest, String> = functions.httpsCallable("timeoutTest")
- // Set a short timeout
- callable.timeoutInterval = 0.01 // 10 milliseconds
- let stream = try callable.stream()
- do {
- for try await _ in stream {
- XCTFail("Expected error to be thrown from stream.")
- }
- } catch let error as FunctionsError where error.code == .unavailable {
- // This should be a timeout error.
- XCTAssertEqual(
- error.localizedDescription,
- "The operation couldn’t be completed. (com.firebase.functions error 14.)"
- )
- XCTAssertNotNil(error.errorUserInfo[NSUnderlyingErrorKey] as? URLError)
- }
- }
- func testStream_LargeData() async throws {
- func generateLargeString() -> String {
- var largeString = ""
- for _ in 0 ..< 10000 {
- largeString += "A"
- }
- return largeString
- }
- let callable: Callable<EmptyRequest, String> = functions.httpsCallable("genStreamLargeData")
- let stream = try callable.stream()
- var concatenatedData = ""
- for try await response in stream {
- concatenatedData += response
- }
- // Assert that the concatenated data matches the expected large data.
- XCTAssertEqual(concatenatedData, generateLargeString())
- }
- }
- // MARK: - Helpers
- 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" }
- }
|