-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_code_generator.rb
64 lines (55 loc) · 1.92 KB
/
test_code_generator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# frozen_string_literal: true
require 'openai'
require_relative 'format_output'
module Dotcodegen
class TestCodeGenerator
attr_reader :config, :file_to_test_path, :openai_key, :openai_org_id
def initialize(config:, file_to_test_path:, openai_key:, openai_org_id: nil)
@config = config
@file_to_test_path = file_to_test_path
@openai_key = openai_key
@openai_org_id = openai_org_id
end
def generate_test_code
response = openai_client.chat(
parameters: {
model: 'gpt-4-turbo-preview',
messages: [{ role: 'user', content: test_prompt_text }], # Required.
temperature: 0.7
}
)
FormatOutput.format(response.dig('choices', 0, 'message', 'content'))
end
def test_prompt_text
[{ "type": 'text', "text": test_prompt }]
end
# rubocop:disable Metrics/MethodLength
def test_prompt
[
'You are an expert programmer. You have been given a task to write a test file for a given file following some instructions.',
'This is the file you want to test:',
'--start--',
test_file_content,
'--end--',
'Here are the instructions on how to write the test file:',
'--start--',
test_instructions,
'--end--',
"Your answer will be directly written in the file you want to test. Don't include any explanation or comments in your answer that isn't code.",
'You can use the comment syntax to write comments in your answer.'
].join("\n")
end
# rubocop:enable Metrics/MethodLength
def test_file_content
File.open(file_to_test_path).read
end
def test_instructions
config['content']
end
def openai_client
client_options = { access_token: openai_key }
client_options[:organization_id] = openai_org_id unless openai_org_id.nil?
@openai_client ||= OpenAI::Client.new(client_options)
end
end
end