XCTestGen: CLI for automatic XCTest generation using ChatGPT
Nakaoka Rei
Posted on March 14, 2023
Introduction
As the title suggests, I created a tool for automatic generation of Swift's XCTest using ChatGPT, which is very popular nowadays. I will briefly explain how I developed it and how to use it.
I would be happy if you starred it.
Using Swift Packages, we have created a CLI tool. The template is created by executing the following command under the working directory
$ swift package init --type executable
Automatic generation of XCTest
As the title suggests, ChatGPT is used for automatic generation of XCTests, and the following commands are given to ChatGPT to write XCTest.
Please write a unit test (XCTest) of the following Swift code. No explanatory text is required as we would like to save your output as source code as is.
// Sample.swift
class Sample {
func sample(input: String) -> String {
// 任意の処理
}
}
The following libraries were used to utilize OpenAI's API in Swift.
Throw the above instruction to ChatGPT and save the response in the specified folder. If you want to know more details, please see the code in the repository.
funcgenerateXCTest()asyncthrows{letorder="Please write a unit test (XCTest) of the following Swift code. No explanatory text is required as we would like to save your output as source code as is."letcode:Stringdo{code=tryFileManager.readTextFile(atPath:input)}catch{throwXCTestGenError.readCodeError}letprompt=order+"\n\n"+codeletopenAI=OpenAISwift(authToken:key)letresult=tryawaitopenAI.sendCompletion(with:prompt,maxTokens:maxTokens)guardlettestCode=result.choices.first?.textelse{throwXCTestGenError.chatgptResultError}do{tryFileManager.saveTextFile(text:testCode,atPath:outputTestsPath())}catch{throwXCTestGenError.saveFileError}}
Usage
Installation
Execute the following command
$ git clone git@github.com:NakaokaRei/XCTestGen.git
$ cd XCTestGen
$ swift build -c release
$ cp .build/release/XCTestGen /usr/local/bin/XCTestGen
Generate XCTest
Execute the following command. In order from the first argument, "API Key of OpenAI", "Path of the Swift file for which you want to automatically generate tests", and "Directory of the output destination".
$ XCTestGen $OPENAI_KEY "input file path" "output dir path"
The current issue is that the test code generated from ChatGPT is not checked for grammatical correctness, so I think it would be better to use SwiftLint or other tools to perform at least some checks.
In the future, we plan to add a plugin function to Swift Package Manger so that it can be easily introduced into Xcode projects.