Skip to content

Commit acfe8cf

Browse files
authored
test: Add more tests (#5)
1 parent a222338 commit acfe8cf

File tree

4 files changed

+138
-46
lines changed

4 files changed

+138
-46
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ ___
2828
1. In your Go code, import the ChatGPT-Go package:
2929
```go
3030
import (
31-
"github.com/<username>/chatgpt-go/chatgpt"
31+
"github.com/ayush6624/chatgpt-go/chatgpt"
3232
)
3333
```
3434

chat.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,7 @@ func (c *Client) Send(ctx context.Context, req *ChatCompletionRequest) (*ChatRes
111111
return nil, err
112112
}
113113

114-
reqBytes, err := json.Marshal(req)
115-
if err != nil {
116-
return nil, err
117-
}
114+
reqBytes, _ := json.Marshal(req)
118115

119116
endpoint := "/chat/completions"
120117
httpReq, err := http.NewRequest("POST", c.config.BaseURL+endpoint, bytes.NewBuffer(reqBytes))

chat_test.go

Lines changed: 125 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package chatgpt
22

33
import (
4+
"context"
5+
"net/http"
6+
"net/http/httptest"
47
"testing"
58

6-
"github.com/stretchr/testify/assert"
79
chatgpt_errors "github.com/ayush6624/go-chatgpt/utils"
10+
"github.com/stretchr/testify/assert"
811
)
912

1013
func TestValidate(t *testing.T) {
@@ -56,9 +59,9 @@ func TestValidate(t *testing.T) {
5659
{
5760
name: "Invalid presence penalty",
5861
request: &ChatCompletionRequest{
59-
Model: GPT35Turbo,
60-
Messages: validRequest().Messages,
61-
PresencePenalty: -3,
62+
Model: GPT35Turbo,
63+
Messages: validRequest().Messages,
64+
PresencePenalty: -3,
6265
},
6366
expectedError: chatgpt_errors.ErrInvalidPresencePenalty,
6467
},
@@ -92,3 +95,121 @@ func validRequest() *ChatCompletionRequest {
9295
},
9396
}
9497
}
98+
99+
func newTestServerAndClient() (*httptest.Server, *Client) {
100+
// Create a new test HTTP server to handle requests
101+
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
102+
w.WriteHeader(http.StatusOK)
103+
w.Write([]byte(`{ "id": "chatcmpl-abcd", "object": "chat.completion", "created_at": 0, "choices": [ { "index": 0, "message": { "role": "assistant", "content": "\n\n Sample response" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 19, "completion_tokens": 47, "total_tokens": 66 }}`))
104+
}))
105+
106+
// Create a new client with the test server's URL and a mock API key
107+
return testServer, &Client{
108+
client: http.DefaultClient,
109+
config: &Config{
110+
BaseURL: testServer.URL,
111+
APIKey: "mock_api_key",
112+
OrganizationID: "mock_organization_id",
113+
},
114+
}
115+
}
116+
117+
func newTestClientWithInvalidResponse() (*httptest.Server, *Client) {
118+
// Create a new test HTTP server to handle requests
119+
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
120+
w.WriteHeader(http.StatusOK)
121+
w.Write([]byte(`{ fakejson }`))
122+
}))
123+
124+
// Create a new client with the test server's URL and a mock API key
125+
return testServer, &Client{
126+
client: http.DefaultClient,
127+
config: &Config{
128+
BaseURL: testServer.URL,
129+
APIKey: "mock_api_key",
130+
OrganizationID: "mock_organization_id",
131+
},
132+
}
133+
}
134+
135+
func newTestClientWithInvalidStatusCode() (*httptest.Server, *Client) {
136+
// Create a new test HTTP server to handle requests
137+
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
138+
w.WriteHeader(http.StatusInternalServerError)
139+
w.Write([]byte(`{ "error": "bad request" }`))
140+
}))
141+
142+
// Create a new client with the test server's URL and a mock API key
143+
return testServer, &Client{
144+
client: http.DefaultClient,
145+
config: &Config{
146+
BaseURL: testServer.URL,
147+
APIKey: "mock_api_key",
148+
OrganizationID: "mock_organization_id",
149+
},
150+
}
151+
}
152+
153+
func TestSend(t *testing.T) {
154+
server, client := newTestServerAndClient()
155+
defer server.Close()
156+
157+
_, err := client.Send(context.Background(), &ChatCompletionRequest{
158+
Model: GPT35Turbo,
159+
Messages: []ChatMessage{
160+
{
161+
Role: ChatGPTModelRoleUser,
162+
Content: "Hello",
163+
},
164+
},
165+
})
166+
assert.NoError(t, err)
167+
168+
_, err = client.Send(context.Background(), &ChatCompletionRequest{
169+
Model: "invalid model",
170+
Messages: []ChatMessage{
171+
{
172+
Role: ChatGPTModelRoleUser,
173+
Content: "Hello",
174+
},
175+
},
176+
})
177+
assert.Error(t, err)
178+
179+
server, client = newTestClientWithInvalidResponse()
180+
defer server.Close()
181+
182+
_, err = client.Send(context.Background(), &ChatCompletionRequest{
183+
Model: GPT35Turbo,
184+
Messages: []ChatMessage{
185+
{
186+
Role: ChatGPTModelRoleUser,
187+
Content: "Hello",
188+
},
189+
},
190+
})
191+
assert.Error(t, err)
192+
193+
server, client = newTestClientWithInvalidStatusCode()
194+
defer server.Close()
195+
196+
_, err = client.Send(context.Background(), &ChatCompletionRequest{
197+
Model: GPT35Turbo,
198+
Messages: []ChatMessage{
199+
{
200+
Role: ChatGPTModelRoleUser,
201+
Content: "Hello",
202+
},
203+
},
204+
})
205+
assert.Error(t, err)
206+
207+
}
208+
209+
func TestSimpleSend(t *testing.T) {
210+
server, client := newTestServerAndClient()
211+
defer server.Close()
212+
213+
_, err := client.SimpleSend(context.Background(), "Hello")
214+
assert.NoError(t, err)
215+
}

client_test.go

Lines changed: 11 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ import (
44
"context"
55
"fmt"
66
"net/http"
7-
"net/http/httptest"
87
"testing"
98

10-
"github.com/ayush6624/go-chatgpt/utils"
9+
chatgpt_errors "github.com/ayush6624/go-chatgpt/utils"
1110
"github.com/stretchr/testify/assert"
1211
)
1312

@@ -32,30 +31,17 @@ func TestNewClient(t *testing.T) {
3231
}
3332

3433
func TestClient2_sendRequest(t *testing.T) {
35-
// Create a new test HTTP server to handle requests
36-
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
37-
w.WriteHeader(http.StatusOK)
38-
}))
39-
defer testServer.Close()
40-
41-
// Create a new client with the test server's URL and a mock API key
42-
client := &Client{
43-
client: http.DefaultClient,
44-
config: &Config{
45-
BaseURL: testServer.URL,
46-
APIKey: "mock_api_key",
47-
OrganizationID: "mock_organization_id",
48-
},
49-
}
34+
// Create a new test HTTP server and client to handle requests
35+
testServer, client := newTestServerAndClient()
5036

5137
// Create a new request
52-
req, err := http.NewRequest("GET", testServer.URL, nil)
38+
req, err := http.NewRequest("POST", testServer.URL, nil)
5339
assert.NoError(t, err)
5440

5541
// Send the request using the ChatGPT client
56-
resp, err := client.sendRequest(context.Background(), req)
42+
res, err := client.sendRequest(context.Background(), req)
5743
assert.NoError(t, err)
58-
assert.Equal(t, http.StatusOK, resp.StatusCode)
44+
assert.Equal(t, http.StatusOK, res.StatusCode)
5945

6046
expectedHeader := map[string]string{
6147
"Authorization": fmt.Sprintf("Bearer %s", "mock_api_key"),
@@ -64,29 +50,17 @@ func TestClient2_sendRequest(t *testing.T) {
6450
"Accept": "application/json",
6551
}
6652

67-
// Check that the request's header is set correctly
53+
// Check that the request's header is set correctly, after sendRequest was called
6854
for key, value := range expectedHeader {
6955
assert.Equal(t, req.Header.Get(key), value)
7056
}
7157

72-
tServer2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
73-
w.WriteHeader(http.StatusBadRequest)
74-
w.Write([]byte(`{"result": "failure"}`))
75-
}))
76-
defer tServer2.Close()
77-
78-
client, err = NewClientWithConfig(&Config{
79-
BaseURL: tServer2.URL,
80-
APIKey: "mock_api_key",
81-
OrganizationID: "mock_organization_id",
82-
})
83-
assert.NoError(t, err)
84-
58+
testServer, client = newTestClientWithInvalidStatusCode()
8559
// Prepare a test request
86-
req, err = http.NewRequest("GET", tServer2.URL, nil)
60+
req, err = http.NewRequest("GET", testServer.URL, nil)
8761
assert.NoError(t, err)
8862

89-
// Send the request using the ChatGPT client
90-
resp, err = client.sendRequest(context.Background(), req)
63+
resp, err := client.sendRequest(context.Background(), req)
9164
assert.Error(t, err)
65+
assert.Nil(t, resp)
9266
}

0 commit comments

Comments
 (0)