ModelContentTests.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2024 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 11.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  18. final class ModelContentTests: XCTestCase {
  19. let decoder = JSONDecoder()
  20. let encoder = JSONEncoder()
  21. override func setUp() {
  22. encoder.outputFormatting = .init(
  23. arrayLiteral: .prettyPrinted, .sortedKeys, .withoutEscapingSlashes
  24. )
  25. }
  26. // MARK: - ModelContent.Part Decoding
  27. func testDecodeFunctionResponsePart() throws {
  28. let functionName = "test-function-name"
  29. let resultParameter = "test-result-parameter"
  30. let resultValue = "test-result-value"
  31. let json = """
  32. {
  33. "functionResponse" : {
  34. "name" : "\(functionName)",
  35. "response" : {
  36. "\(resultParameter)" : "\(resultValue)"
  37. }
  38. }
  39. }
  40. """
  41. let jsonData = try XCTUnwrap(json.data(using: .utf8))
  42. let part = try decoder.decode(ModelContent.Part.self, from: jsonData)
  43. guard case let .functionResponse(functionResponse) = part else {
  44. XCTFail("Decoded Part was not a FunctionResponse.")
  45. return
  46. }
  47. XCTAssertEqual(functionResponse.name, functionName)
  48. XCTAssertEqual(functionResponse.response, [resultParameter: .string(resultValue)])
  49. }
  50. // MARK: - ModelContent.Part Encoding
  51. func testEncodeFileDataPart() throws {
  52. let mimeType = "image/jpeg"
  53. let fileURI = "gs://test-bucket/image.jpg"
  54. let fileDataPart = ModelContent.Part.fileData(mimetype: mimeType, uri: fileURI)
  55. let jsonData = try encoder.encode(fileDataPart)
  56. let json = try XCTUnwrap(String(data: jsonData, encoding: .utf8))
  57. XCTAssertEqual(json, """
  58. {
  59. "fileData" : {
  60. "file_uri" : "\(fileURI)",
  61. "mime_type" : "\(mimeType)"
  62. }
  63. }
  64. """)
  65. }
  66. }