ChatTests.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2023 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 XCTest
  16. @testable import FirebaseVertexAI
  17. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, *)
  18. final class ChatTests: XCTestCase {
  19. var urlSession: URLSession!
  20. override func setUp() {
  21. let configuration = URLSessionConfiguration.default
  22. configuration.protocolClasses = [MockURLProtocol.self]
  23. urlSession = URLSession(configuration: configuration)
  24. }
  25. override func tearDown() {
  26. MockURLProtocol.requestHandler = nil
  27. }
  28. func testMergingText() async throws {
  29. let fileURL = try XCTUnwrap(Bundle.module.url(
  30. forResource: "streaming-success-basic-reply-parts",
  31. withExtension: "txt"
  32. ))
  33. MockURLProtocol.requestHandler = { request in
  34. let response = HTTPURLResponse(
  35. url: request.url!,
  36. statusCode: 200,
  37. httpVersion: nil,
  38. headerFields: nil
  39. )!
  40. return (response, fileURL.lines)
  41. }
  42. let model = GenerativeModel(
  43. name: "my-model",
  44. projectID: "my-project-id",
  45. apiKey: "API_KEY",
  46. tools: nil,
  47. requestOptions: RequestOptions(),
  48. appCheck: nil,
  49. auth: nil,
  50. urlSession: urlSession
  51. )
  52. let chat = Chat(model: model, history: [])
  53. let input = "Test input"
  54. let stream = chat.sendMessageStream(input)
  55. // Ensure the values are parsed correctly
  56. for try await value in stream {
  57. XCTAssertNotNil(value.text)
  58. }
  59. XCTAssertEqual(chat.history.count, 2)
  60. XCTAssertEqual(chat.history[0].parts[0].text, input)
  61. let finalText = "1 2 3 4 5 6 7 8"
  62. let assembledExpectation = ModelContent(role: "model", parts: finalText)
  63. XCTAssertEqual(chat.history[0].parts[0].text, input)
  64. XCTAssertEqual(chat.history[1], assembledExpectation)
  65. }
  66. }