Skip to content

[Firebase AI] Add GenerativeModel tests using Dev API mock responses #14816

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion FirebaseAI.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Build AI-powered apps and features with the Gemini API using the Firebase AI SDK
unit_tests_dir + 'Snippets/**/*.swift',
]
unit_tests.resources = [
unit_tests_dir + 'vertexai-sdk-test-data/mock-responses/vertexai',
unit_tests_dir + 'vertexai-sdk-test-data/mock-responses',
unit_tests_dir + 'Resources/**/*',
]
end
Expand Down
85 changes: 43 additions & 42 deletions FirebaseAI/Tests/Unit/ChatTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,57 +40,58 @@ final class ChatTests: XCTestCase {
let fileURL = try XCTUnwrap(bundle.url(
forResource: "streaming-success-basic-reply-parts",
withExtension: "txt",
subdirectory: "vertexai"
subdirectory: "mock-responses/vertexai"
))

// Skip tests using MockURLProtocol on watchOS; unsupported in watchOS 2 and later, see
// https://developer.apple.com/documentation/foundation/urlprotocol for details.
#if os(watchOS)
throw XCTSkip("Custom URL protocols are unsupported in watchOS 2 and later.")
#endif // os(watchOS)
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: nil,
headerFields: nil
)!
return (response, fileURL.lines)
}
#else // os(watchOS)
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: nil,
headerFields: nil
)!
return (response, fileURL.lines)
}

let app = FirebaseApp(instanceWithName: "testApp",
options: FirebaseOptions(googleAppID: "ignore",
gcmSenderID: "ignore"))
let model = GenerativeModel(
modelName: modelName,
modelResourceName: modelResourceName,
firebaseInfo: FirebaseInfo(
projectID: "my-project-id",
apiKey: "API_KEY",
firebaseAppID: "My app ID",
firebaseApp: app
),
apiConfig: FirebaseAI.defaultVertexAIAPIConfig,
tools: nil,
requestOptions: RequestOptions(),
urlSession: urlSession
)
let chat = Chat(model: model, history: [])
let input = "Test input"
let stream = try chat.sendMessageStream(input)
let app = FirebaseApp(instanceWithName: "testApp",
options: FirebaseOptions(googleAppID: "ignore",
gcmSenderID: "ignore"))
let model = GenerativeModel(
modelName: modelName,
modelResourceName: modelResourceName,
firebaseInfo: FirebaseInfo(
projectID: "my-project-id",
apiKey: "API_KEY",
firebaseAppID: "My app ID",
firebaseApp: app
),
apiConfig: FirebaseAI.defaultVertexAIAPIConfig,
tools: nil,
requestOptions: RequestOptions(),
urlSession: urlSession
)
let chat = Chat(model: model, history: [])
let input = "Test input"
let stream = try chat.sendMessageStream(input)

// Ensure the values are parsed correctly
for try await value in stream {
XCTAssertNotNil(value.text)
}
// Ensure the values are parsed correctly
for try await value in stream {
XCTAssertNotNil(value.text)
}

XCTAssertEqual(chat.history.count, 2)
let part = try XCTUnwrap(chat.history[0].parts[0])
let textPart = try XCTUnwrap(part as? TextPart)
XCTAssertEqual(textPart.text, input)
XCTAssertEqual(chat.history.count, 2)
let part = try XCTUnwrap(chat.history[0].parts[0])
let textPart = try XCTUnwrap(part as? TextPart)
XCTAssertEqual(textPart.text, input)

let finalText = "1 2 3 4 5 6 7 8"
let assembledExpectation = ModelContent(role: "model", parts: finalText)
XCTAssertEqual(chat.history[1], assembledExpectation)
let finalText = "1 2 3 4 5 6 7 8"
let assembledExpectation = ModelContent(role: "model", parts: finalText)
XCTAssertEqual(chat.history[1], assembledExpectation)
#endif // os(watchOS)
}
}
66 changes: 66 additions & 0 deletions FirebaseAI/Tests/Unit/Fakes/AppCheckInteropFake.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright 2025 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 FirebaseAppCheckInterop
import Foundation

@available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
class AppCheckInteropFake: NSObject, AppCheckInterop {
/// The placeholder token value returned when an error occurs
static let placeholderTokenValue = "placeholder-token"

var token: String
var error: Error?

private init(token: String, error: Error?) {
self.token = token
self.error = error
}

convenience init(token: String) {
self.init(token: token, error: nil)
}

convenience init(error: Error) {
self.init(token: AppCheckInteropFake.placeholderTokenValue, error: error)
}

func getToken(forcingRefresh: Bool) async -> any FIRAppCheckTokenResultInterop {
return AppCheckTokenResultInteropFake(token: token, error: error)
}

func tokenDidChangeNotificationName() -> String {
fatalError("\(#function) not implemented.")
}

func notificationTokenKey() -> String {
fatalError("\(#function) not implemented.")
}

func notificationAppNameKey() -> String {
fatalError("\(#function) not implemented.")
}

private class AppCheckTokenResultInteropFake: NSObject, FIRAppCheckTokenResultInterop {
var token: String
var error: Error?

init(token: String, error: Error?) {
self.token = token
self.error = error
}
}
}

struct AppCheckErrorFake: Error {}
Loading
Loading