@@ -288,6 +288,60 @@ final class GenerativeModelTests: XCTestCase {
288
288
XCTAssertEqual ( text, " The sum of [1, 2, \n 3] is " )
289
289
}
290
290
291
+ func testGenerateContent_success_codeExecution( ) async throws {
292
+ MockURLProtocol
293
+ . requestHandler = try httpRequestHandler (
294
+ forResource: " unary-success-code-execution " ,
295
+ withExtension: " json "
296
+ )
297
+ let expectedText1 = """
298
+ To print strings in Python, you use the `print()` function. \
299
+ Here's how you can print \" Hello, world! \" : \n \n
300
+ """
301
+ let expectedText2 = " The code successfully prints the string \" Hello, world! \" . \n "
302
+ let expectedLanguage = " PYTHON "
303
+ let expectedCode = " \n print( \" Hello, world! \" ) \n "
304
+ let expectedOutput = " Hello, world! \n "
305
+
306
+ let response = try await model. generateContent ( testPrompt)
307
+
308
+ XCTAssertEqual ( response. candidates. count, 1 )
309
+ let candidate = try XCTUnwrap ( response. candidates. first)
310
+ XCTAssertEqual ( candidate. content. parts. count, 4 )
311
+ guard case let . text( text1) = candidate. content. parts [ 0 ] else {
312
+ XCTFail ( " Expected first part to be text. " )
313
+ return
314
+ }
315
+ XCTAssertEqual ( text1, expectedText1)
316
+ guard case let . executableCode( executableCode) = candidate. content. parts [ 1 ] else {
317
+ XCTFail ( " Expected second part to be executable code. " )
318
+ return
319
+ }
320
+ XCTAssertEqual ( executableCode. language, expectedLanguage)
321
+ XCTAssertEqual ( executableCode. code, expectedCode)
322
+ guard case let . codeExecutionResult( codeExecutionResult) = candidate. content. parts [ 2 ] else {
323
+ XCTFail ( " Expected second part to be a code execution result. " )
324
+ return
325
+ }
326
+ XCTAssertEqual ( codeExecutionResult. outcome, . ok)
327
+ XCTAssertEqual ( codeExecutionResult. output, expectedOutput)
328
+ guard case let . text( text2) = candidate. content. parts [ 3 ] else {
329
+ XCTFail ( " Expected fourth part to be text. " )
330
+ return
331
+ }
332
+ XCTAssertEqual ( text2, expectedText2)
333
+ XCTAssertEqual ( try XCTUnwrap ( response. text) , """
334
+ \( expectedText1)
335
+ ``` \( expectedLanguage. lowercased ( ) )
336
+ \( expectedCode)
337
+ ```
338
+ ```
339
+ \( expectedOutput)
340
+ ```
341
+ \( expectedText2)
342
+ """ )
343
+ }
344
+
291
345
func testGenerateContent_usageMetadata( ) async throws {
292
346
MockURLProtocol
293
347
. requestHandler = try httpRequestHandler (
0 commit comments