-
Notifications
You must be signed in to change notification settings - Fork 38
/
integration_test.go
955 lines (726 loc) · 31.8 KB
/
integration_test.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
package integration_test
import (
"encoding/json"
"fmt"
"github.com/kardolus/chatgpt-cli/config"
"github.com/kardolus/chatgpt-cli/configmanager"
"github.com/kardolus/chatgpt-cli/history"
"github.com/kardolus/chatgpt-cli/types"
"github.com/kardolus/chatgpt-cli/utils"
"github.com/onsi/gomega/gexec"
"github.com/sclevine/spec"
"github.com/sclevine/spec/report"
"io"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
. "github.com/onsi/gomega"
)
const (
gitCommit = "some-git-commit"
gitVersion = "some-git-version"
servicePort = ":8080"
serviceURL = "http://0.0.0.0" + servicePort
)
var (
once sync.Once
)
func TestIntegration(t *testing.T) {
defer gexec.CleanupBuildArtifacts()
spec.Run(t, "Integration Tests", testIntegration, spec.Report(report.Terminal{}))
}
func testIntegration(t *testing.T, when spec.G, it spec.S) {
it.Before(func() {
RegisterTestingT(t)
Expect(os.Unsetenv(utils.ConfigHomeEnv)).To(Succeed())
Expect(os.Unsetenv(utils.DataHomeEnv)).To(Succeed())
})
when("Read and Write History", func() {
const threadName = "default-thread"
var (
tmpDir string
fileIO *history.FileIO
messages []types.Message
err error
)
it.Before(func() {
tmpDir, err = os.MkdirTemp("", "chatgpt-cli-test")
Expect(err).NotTo(HaveOccurred())
fileIO, _ = history.New()
fileIO = fileIO.WithDirectory(tmpDir)
fileIO.SetThread(threadName)
messages = []types.Message{
{
Role: "user",
Content: "Test message 1",
},
{
Role: "assistant",
Content: "Test message 2",
},
}
})
it.After(func() {
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
it("writes the messages to the file", func() {
err = fileIO.Write(messages)
Expect(err).NotTo(HaveOccurred())
})
it("reads the messages from the file", func() {
err = fileIO.Write(messages) // need to write before reading
Expect(err).NotTo(HaveOccurred())
readMessages, err := fileIO.Read()
Expect(err).NotTo(HaveOccurred())
Expect(readMessages).To(Equal(messages))
})
})
when("Read, Write, List, Delete Config", func() {
var (
tmpDir string
tmpFile *os.File
historyDir string
configIO *config.FileIO
testConfig types.Config
err error
)
it.Before(func() {
tmpDir, err = os.MkdirTemp("", "chatgpt-cli-test")
Expect(err).NotTo(HaveOccurred())
historyDir, err = os.MkdirTemp(tmpDir, "history")
Expect(err).NotTo(HaveOccurred())
tmpFile, err = os.CreateTemp(tmpDir, "config.yaml")
Expect(err).NotTo(HaveOccurred())
Expect(tmpFile.Close()).To(Succeed())
configIO = config.New().WithConfigPath(tmpFile.Name()).WithHistoryPath(historyDir)
testConfig = types.Config{
Model: "test-model",
}
})
it.After(func() {
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
when("performing a migration", func() {
defaults := config.New().ReadDefaults()
it("it doesn't apply a migration when max_tokens is 0", func() {
testConfig.MaxTokens = 0
err = configIO.Write(testConfig) // need to write before reading
Expect(err).NotTo(HaveOccurred())
readConfig, err := configIO.Read()
Expect(err).NotTo(HaveOccurred())
Expect(readConfig).To(Equal(testConfig))
})
it("it migrates small values of max_tokens as expected", func() {
testConfig.MaxTokens = defaults.ContextWindow - 1
err = configIO.Write(testConfig) // need to write before reading
Expect(err).NotTo(HaveOccurred())
readConfig, err := configIO.Read()
Expect(err).NotTo(HaveOccurred())
expectedConfig := testConfig
expectedConfig.MaxTokens = defaults.MaxTokens
expectedConfig.ContextWindow = defaults.ContextWindow
Expect(readConfig).To(Equal(expectedConfig))
})
it("it migrates large values of max_tokens as expected", func() {
testConfig.MaxTokens = defaults.ContextWindow + 1
err = configIO.Write(testConfig) // need to write before reading
Expect(err).NotTo(HaveOccurred())
readConfig, err := configIO.Read()
Expect(err).NotTo(HaveOccurred())
expectedConfig := testConfig
expectedConfig.MaxTokens = defaults.MaxTokens
expectedConfig.ContextWindow = testConfig.MaxTokens
Expect(readConfig).To(Equal(expectedConfig))
})
})
it("lists all the threads", func() {
files := []string{"thread1.json", "thread2.json", "thread3.json"}
for _, file := range files {
file, err := os.Create(filepath.Join(historyDir, file))
Expect(err).NotTo(HaveOccurred())
Expect(file.Close()).To(Succeed())
}
result, err := configIO.List()
Expect(err).NotTo(HaveOccurred())
Expect(result).To(HaveLen(3))
Expect(result[2]).To(Equal("thread3.json"))
})
it("deletes the thread", func() {
files := []string{"thread1.json", "thread2.json", "thread3.json"}
for _, file := range files {
file, err := os.Create(filepath.Join(historyDir, file))
Expect(err).NotTo(HaveOccurred())
Expect(file.Close()).To(Succeed())
}
err = configIO.Delete("thread2")
Expect(err).NotTo(HaveOccurred())
_, err = os.Stat(filepath.Join(historyDir, "thread2.json"))
Expect(os.IsNotExist(err)).To(BeTrue())
_, err = os.Stat(filepath.Join(historyDir, "thread3.json"))
Expect(os.IsNotExist(err)).To(BeFalse())
})
})
when("Performing the Lifecycle", func() {
const (
exitSuccess = 0
exitFailure = 1
)
var (
homeDir string
filePath string
configFile string
err error
apiKeyEnvVar string
)
runCommand := func(args ...string) string {
command := exec.Command(binaryPath, args...)
session, err := gexec.Start(command, io.Discard, io.Discard)
ExpectWithOffset(1, err).NotTo(HaveOccurred())
<-session.Exited
if tmp := string(session.Err.Contents()); tmp != "" {
fmt.Printf("error output: %s", string(session.Err.Contents()))
}
ExpectWithOffset(1, session).Should(gexec.Exit(0))
return string(session.Out.Contents())
}
checkConfigFileContent := func(expectedContent string) {
content, err := os.ReadFile(configFile)
ExpectWithOffset(1, err).NotTo(HaveOccurred())
ExpectWithOffset(1, string(content)).To(ContainSubstring(expectedContent))
}
it.Before(func() {
once.Do(func() {
SetDefaultEventuallyTimeout(10 * time.Second)
log.Println("Building binary...")
Expect(buildBinary()).To(Succeed())
log.Println("Binary built successfully!")
log.Println("Starting mock server...")
Expect(runMockServer()).To(Succeed())
log.Println("Mock server started!")
Eventually(func() (string, error) {
return curl(fmt.Sprintf("%s/ping", serviceURL))
}).Should(ContainSubstring("pong"))
})
homeDir, err = os.MkdirTemp("", "mockHome")
Expect(err).NotTo(HaveOccurred())
apiKeyEnvVar = configmanager.New(config.New()).WithEnvironment().APIKeyEnvVarName()
Expect(os.Setenv("HOME", homeDir)).To(Succeed())
Expect(os.Setenv(apiKeyEnvVar, expectedToken)).To(Succeed())
})
it.After(func() {
gexec.Kill()
Expect(os.RemoveAll(homeDir))
})
it("throws an error when the API key is missing", func() {
Expect(os.Unsetenv(apiKeyEnvVar)).To(Succeed())
command := exec.Command(binaryPath, "some prompt")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("API key is required."))
})
it("should not require an API key for the --version flag", func() {
Expect(os.Unsetenv(apiKeyEnvVar)).To(Succeed())
command := exec.Command(binaryPath, "--version")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitSuccess))
})
it("should require a hidden folder for the --list-threads flag", func() {
command := exec.Command(binaryPath, "--list-threads")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring(".chatgpt-cli/history: no such file or directory"))
})
it("should return an error when --new-thread is used with --set-thread", func() {
command := exec.Command(binaryPath, "--new-thread", "--set-thread", "some-thread")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("the --new-thread flag cannot be used with the --set-thread or --thread flags"))
})
it("should return an error when --new-thread is used with --thread", func() {
command := exec.Command(binaryPath, "--new-thread", "--thread", "some-thread")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("the --new-thread flag cannot be used with the --set-thread or --thread flags"))
})
it("should require an argument for the --set-model flag", func() {
command := exec.Command(binaryPath, "--set-model")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("flag needs an argument: --set-model"))
})
it("should require an argument for the --set-thread flag", func() {
command := exec.Command(binaryPath, "--set-thread")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("flag needs an argument: --set-thread"))
})
it("should require an argument for the --set-max-tokens flag", func() {
command := exec.Command(binaryPath, "--set-max-tokens")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("flag needs an argument: --set-max-tokens"))
})
it("should require an argument for the --set-context-window flag", func() {
command := exec.Command(binaryPath, "--set-context-window")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("flag needs an argument: --set-context-window"))
})
it("should warn when config.yaml does not exist and OPENAI_CONFIG_HOME is set", func() {
configHomeDir := "does-not-exist"
Expect(os.Setenv(utils.ConfigHomeEnv, configHomeDir)).To(Succeed())
configFilePath := path.Join(configHomeDir, "config.yaml")
Expect(configFilePath).NotTo(BeAnExistingFile())
command := exec.Command(binaryPath, "llm query")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitSuccess))
output := string(session.Out.Contents())
Expect(output).To(ContainSubstring(fmt.Sprintf("Warning: config.yaml doesn't exist in %s, create it", configHomeDir)))
// Unset the variable to prevent pollution
Expect(os.Unsetenv(utils.ConfigHomeEnv)).To(Succeed())
})
it("should NOT warn when config.yaml does not exist and OPENAI_CONFIG_HOME is NOT set", func() {
configHomeDir := "does-not-exist"
Expect(os.Unsetenv(utils.ConfigHomeEnv)).To(Succeed())
configFilePath := path.Join(configHomeDir, "config.yaml")
Expect(configFilePath).NotTo(BeAnExistingFile())
command := exec.Command(binaryPath, "llm query")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitSuccess))
output := string(session.Out.Contents())
Expect(output).NotTo(ContainSubstring(fmt.Sprintf("Warning: config.yaml doesn't exist in %s, create it", configHomeDir)))
})
it("should require the chatgpt-cli folder but not an API key for the --set-model flag", func() {
Expect(os.Unsetenv(apiKeyEnvVar)).To(Succeed())
command := exec.Command(binaryPath, "--set-model", "123")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("config directory does not exist:"))
Expect(output).NotTo(ContainSubstring(apiKeyEnvVar))
})
it("should require the chatgpt-cli folder but not an API key for the --set-thread flag", func() {
Expect(os.Unsetenv(apiKeyEnvVar)).To(Succeed())
command := exec.Command(binaryPath, "--set-thread", "thread-name")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("config directory does not exist:"))
Expect(output).NotTo(ContainSubstring(apiKeyEnvVar))
})
it("should require the chatgpt-cli folder but not an API key for the --set-max-tokens flag", func() {
Expect(os.Unsetenv(apiKeyEnvVar)).To(Succeed())
command := exec.Command(binaryPath, "--set-max-tokens", "789")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("config directory does not exist:"))
Expect(output).NotTo(ContainSubstring(apiKeyEnvVar))
})
it("should require the chatgpt-cli folder but not an API key for the --set-context-window flag", func() {
Expect(os.Unsetenv(apiKeyEnvVar)).To(Succeed())
command := exec.Command(binaryPath, "--set-context-window", "789")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
Expect(output).To(ContainSubstring("config directory does not exist:"))
Expect(output).NotTo(ContainSubstring(apiKeyEnvVar))
})
it("should return the expected result for the --version flag", func() {
output := runCommand("--version")
Expect(output).To(ContainSubstring(fmt.Sprintf("commit %s", gitCommit)))
Expect(output).To(ContainSubstring(fmt.Sprintf("version %s", gitVersion)))
})
it("should return the expected result for the --list-models flag", func() {
output := runCommand("--list-models")
Expect(output).To(ContainSubstring("* gpt-3.5-turbo (current)"))
Expect(output).To(ContainSubstring("- gpt-3.5-turbo-0301"))
})
it("should return the expected result for the --query flag", func() {
Expect(os.Setenv("OPENAI_TRACK_TOKEN_USAGE", "false")).To(Succeed())
output := runCommand("--query", "some-query")
expectedResponse := `I don't have personal opinions about bars, but here are some popular bars in Red Hook, Brooklyn:`
Expect(output).To(ContainSubstring(expectedResponse))
Expect(output).NotTo(ContainSubstring("Token Usage:"))
})
it("should display token usage after a query when configured to do so", func() {
Expect(os.Setenv("OPENAI_TRACK_TOKEN_USAGE", "true")).To(Succeed())
output := runCommand("--query", "tell me a 5 line joke")
Expect(output).To(ContainSubstring("Token Usage:"))
})
it("prints debug information with the --debug flag", func() {
Expect(os.Setenv("OPENAI_DEBUG", "true")).To(Succeed())
output := runCommand("--query", "tell me a joke")
Expect(output).To(ContainSubstring("Generated cURL command"))
Expect(output).To(ContainSubstring("/v1/chat/completions"))
Expect(output).To(ContainSubstring("--header \"Authorization: Bearer ${OPENAI_API_KEY}\""))
Expect(output).To(ContainSubstring("--header 'Content-Type: application/json'"))
Expect(output).To(ContainSubstring("\"model\":\"gpt-3.5-turbo\""))
Expect(output).To(ContainSubstring("\"messages\":"))
Expect(output).To(ContainSubstring("Response"))
Expect(os.Unsetenv("OPENAI_DEBUG")).To(Succeed())
})
it("should assemble http errors as expected", func() {
Expect(os.Setenv(apiKeyEnvVar, "wrong-token")).To(Succeed())
command := exec.Command(binaryPath, "--query", "some-query")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitFailure))
output := string(session.Err.Contents())
// see error.json
Expect(output).To(Equal("http status 401: Incorrect API key provided\n"))
})
when("there is a hidden chatgpt-cli folder in the home dir", func() {
it.Before(func() {
filePath = path.Join(os.Getenv("HOME"), ".chatgpt-cli")
Expect(os.MkdirAll(filePath, 0777)).To(Succeed())
})
it.After(func() {
Expect(os.RemoveAll(filePath)).To(Succeed())
})
it("should not require an API key for the --list-threads flag", func() {
historyPath := path.Join(filePath, "history")
Expect(os.MkdirAll(historyPath, 0777)).To(Succeed())
Expect(os.Unsetenv(apiKeyEnvVar)).To(Succeed())
command := exec.Command(binaryPath, "--list-threads")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitSuccess))
})
it("migrates the legacy history as expected", func() {
// Legacy history file should not exist
legacyFile := path.Join(filePath, "history")
Expect(legacyFile).NotTo(BeAnExistingFile())
// History should not exist yet
historyFile := path.Join(filePath, "history", "default.json")
Expect(historyFile).NotTo(BeAnExistingFile())
bytes, err := utils.FileToBytes("history.json")
Expect(err).NotTo(HaveOccurred())
Expect(os.WriteFile(legacyFile, bytes, 0644)).To(Succeed())
Expect(legacyFile).To(BeARegularFile())
// Perform a query
command := exec.Command(binaryPath, "--query", "some-query")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
// The CLI response should be as expected
Eventually(session).Should(gexec.Exit(exitSuccess))
output := string(session.Out.Contents())
response := `I don't have personal opinions about bars, but here are some popular bars in Red Hook, Brooklyn:`
Expect(output).To(ContainSubstring(response))
// The history file should have the expected content
Expect(path.Dir(historyFile)).To(BeADirectory())
content, err := os.ReadFile(historyFile)
Expect(err).NotTo(HaveOccurred())
Expect(content).NotTo(BeEmpty())
Expect(string(content)).To(ContainSubstring(response))
// The legacy file should now be a directory
Expect(legacyFile).To(BeADirectory())
Expect(legacyFile).NotTo(BeARegularFile())
// The content was moved to the new file
Expect(string(content)).To(ContainSubstring("Of course! Which city are you referring to?"))
})
it("should not require an API key for the --clear-history flag", func() {
Expect(os.Unsetenv(apiKeyEnvVar)).To(Succeed())
command := exec.Command(binaryPath, "--clear-history")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitSuccess))
})
it("keeps track of history", func() {
// History should not exist yet
historyDir := path.Join(filePath, "history")
historyFile := path.Join(historyDir, "default.json")
Expect(historyFile).NotTo(BeAnExistingFile())
// Perform a query and check response
response := `I don't have personal opinions about bars, but here are some popular bars in Red Hook, Brooklyn:`
output := runCommand("--query", "some-query")
Expect(output).To(ContainSubstring(response))
// Check if history file was created with expected content
Expect(historyDir).To(BeADirectory())
checkHistoryContent := func(expectedContent string) {
content, err := os.ReadFile(historyFile)
Expect(err).NotTo(HaveOccurred())
Expect(string(content)).To(ContainSubstring(expectedContent))
}
checkHistoryContent(response)
// Clear the history using the CLI
runCommand("--clear-history")
Expect(historyFile).NotTo(BeAnExistingFile())
// Test omitting history through environment variable
omitHistoryEnvKey := strings.Replace(apiKeyEnvVar, "API_KEY", "OMIT_HISTORY", 1)
envValue := "true"
Expect(os.Setenv(omitHistoryEnvKey, envValue)).To(Succeed())
// Perform another query with history omitted
runCommand("--query", "some-query")
// The history file should NOT be recreated
Expect(historyFile).NotTo(BeAnExistingFile())
// Cleanup: Unset the environment variable
Expect(os.Unsetenv(omitHistoryEnvKey)).To(Succeed())
})
it("should return the expected result for the --list-threads flag", func() {
historyDir := path.Join(filePath, "history")
Expect(os.Mkdir(historyDir, 0755)).To(Succeed())
files := []string{"thread1.json", "thread2.json", "thread3.json", "default.json"}
Expect(os.MkdirAll(historyDir, 7555)).To(Succeed())
for _, file := range files {
file, err := os.Create(filepath.Join(historyDir, file))
Expect(err).NotTo(HaveOccurred())
Expect(file.Close()).To(Succeed())
}
output := runCommand("--list-threads")
Expect(output).To(ContainSubstring("* default (current)"))
Expect(output).To(ContainSubstring("- thread1"))
Expect(output).To(ContainSubstring("- thread2"))
Expect(output).To(ContainSubstring("- thread3"))
})
it("should delete the expected thread using the --delete-threads flag", func() {
historyDir := path.Join(filePath, "history")
Expect(os.Mkdir(historyDir, 0755)).To(Succeed())
files := []string{"thread1.json", "thread2.json", "thread3.json", "default.json"}
Expect(os.MkdirAll(historyDir, 7555)).To(Succeed())
for _, file := range files {
file, err := os.Create(filepath.Join(historyDir, file))
Expect(err).NotTo(HaveOccurred())
Expect(file.Close()).To(Succeed())
}
runCommand("--delete-thread", "thread2")
output := runCommand("--list-threads")
Expect(output).To(ContainSubstring("* default (current)"))
Expect(output).To(ContainSubstring("- thread1"))
Expect(output).NotTo(ContainSubstring("- thread2"))
Expect(output).To(ContainSubstring("- thread3"))
})
it("should not throw an error when a non-existent thread is deleted using the --delete-threads flag", func() {
command := exec.Command(binaryPath, "--delete-thread", "does-not-exist")
session, err := gexec.Start(command, io.Discard, io.Discard)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(exitSuccess))
})
when("configurable flags are set", func() {
it.Before(func() {
configFile = path.Join(filePath, "config.yaml")
Expect(configFile).NotTo(BeAnExistingFile())
})
it("has a configurable default model", func() {
oldModel := "gpt-3.5-turbo"
newModel := "gpt-3.5-turbo-0301"
// Verify initial model
output := runCommand("--list-models")
Expect(output).To(ContainSubstring("* " + oldModel + " (current)"))
Expect(output).To(ContainSubstring("- " + newModel))
// Update model
runCommand("--set-model", newModel)
// Check configFile is created and contains the new model
Expect(configFile).To(BeAnExistingFile())
checkConfigFileContent(newModel)
// Verify updated model through --list-models
output = runCommand("--list-models")
Expect(output).To(ContainSubstring("* " + newModel + " (current)"))
})
it("has a configurable default context-window", func() {
defaults := config.New().ReadDefaults()
// Initial check for default context-window
output := runCommand("--config")
Expect(output).To(ContainSubstring(strconv.Itoa(defaults.ContextWindow)))
// Update and verify context-window
newContextWindow := "100000"
runCommand("--set-context-window", newContextWindow)
Expect(configFile).To(BeAnExistingFile())
checkConfigFileContent(newContextWindow)
// Verify update through --config
output = runCommand("--config")
Expect(output).To(ContainSubstring(newContextWindow))
// Environment variable takes precedence
envContext := "123"
modelEnvKey := strings.Replace(apiKeyEnvVar, "API_KEY", "CONTEXT_WINDOW", 1)
Expect(os.Setenv(modelEnvKey, envContext)).To(Succeed())
// Verify environment variable override
output = runCommand("--config")
Expect(output).To(ContainSubstring(envContext))
Expect(os.Unsetenv(modelEnvKey)).To(Succeed())
})
it("has a configurable default max-tokens", func() {
defaults := config.New().ReadDefaults()
// Initial check for default max-tokens
output := runCommand("--config")
Expect(output).To(ContainSubstring(strconv.Itoa(defaults.MaxTokens)))
// Update and verify max-tokens
newMaxTokens := "81724"
runCommand("--set-max-tokens", newMaxTokens)
Expect(configFile).To(BeAnExistingFile())
checkConfigFileContent(newMaxTokens)
// Verify update through --config
output = runCommand("--config")
Expect(output).To(ContainSubstring(newMaxTokens))
// Environment variable takes precedence
modelEnvKey := strings.Replace(apiKeyEnvVar, "API_KEY", "MAX_TOKENS", 1)
Expect(os.Setenv(modelEnvKey, newMaxTokens)).To(Succeed())
// Verify environment variable override
output = runCommand("--config")
Expect(output).To(ContainSubstring(newMaxTokens))
Expect(os.Unsetenv(modelEnvKey)).To(Succeed())
})
it("has a configurable default thread", func() {
defaults := config.New().ReadDefaults()
// Initial check for default thread
output := runCommand("--config")
Expect(output).To(ContainSubstring(defaults.Thread))
// Update and verify thread
newThread := "new-thread"
runCommand("--set-thread", newThread)
Expect(configFile).To(BeAnExistingFile())
checkConfigFileContent(newThread)
// Verify update through --config
output = runCommand("--config")
Expect(output).To(ContainSubstring(newThread))
// Environment variable takes precedence
threadEnvKey := strings.Replace(apiKeyEnvVar, "API_KEY", "THREAD", 1)
Expect(os.Setenv(threadEnvKey, newThread)).To(Succeed())
// Verify environment variable override
output = runCommand("--config")
Expect(output).To(ContainSubstring(newThread))
Expect(os.Unsetenv(threadEnvKey)).To(Succeed())
})
})
})
when("configuration precedence", func() {
var (
defaultModel = "gpt-3.5-turbo"
newModel = "gpt-3.5-turbo-0301"
envModel = "gpt-3.5-env-model"
envVar string
)
it.Before(func() {
envVar = strings.Replace(apiKeyEnvVar, "API_KEY", "MODEL", 1)
filePath = path.Join(os.Getenv("HOME"), ".chatgpt-cli")
Expect(os.MkdirAll(filePath, 0777)).To(Succeed())
configFile = path.Join(filePath, "config.yaml")
Expect(configFile).NotTo(BeAnExistingFile())
})
it("uses environment variable over config file", func() {
// Step 1: Set a model in the config file.
runCommand("--set-model", newModel)
checkConfigFileContent(newModel)
// Step 2: Verify the model from config is used.
output := runCommand("--list-models")
Expect(output).To(ContainSubstring("* " + newModel + " (current)"))
// Step 3: Set environment variable and verify it takes precedence.
Expect(os.Setenv(envVar, envModel)).To(Succeed())
output = runCommand("--list-models")
Expect(output).To(ContainSubstring("* " + envModel + " (current)"))
// Step 4: Unset environment variable and verify it falls back to config file.
Expect(os.Unsetenv(envVar)).To(Succeed())
output = runCommand("--list-models")
Expect(output).To(ContainSubstring("* " + newModel + " (current)"))
})
it("uses command-line flag over environment variable", func() {
// Step 1: Set environment variable.
Expect(os.Setenv(envVar, envModel)).To(Succeed())
// Step 2: Verify environment variable does not override flag.
output := runCommand("--model", newModel, "--list-models")
Expect(output).To(ContainSubstring("* " + newModel + " (current)"))
})
it("falls back to default when config and env are absent", func() {
// Step 1: Ensure no config file and no environment variable.
Expect(os.Unsetenv(envVar)).To(Succeed())
// Step 2: Verify it falls back to the default model.
output := runCommand("--list-models")
Expect(output).To(ContainSubstring("* " + defaultModel + " (current)"))
})
})
when("show-history flag is used", func() {
var tmpDir string
var err error
var historyFile string
it.Before(func() {
RegisterTestingT(t)
tmpDir, err = os.MkdirTemp("", "chatgpt-cli-test")
Expect(err).NotTo(HaveOccurred())
historyFile = filepath.Join(tmpDir, "default.json")
messages := []types.Message{
{Role: "user", Content: "Hello"},
{Role: "assistant", Content: "Hi, how can I help you?"},
{Role: "user", Content: "Tell me about the weather"},
{Role: "assistant", Content: "It's sunny today."},
}
data, err := json.Marshal(messages)
Expect(err).NotTo(HaveOccurred())
Expect(os.WriteFile(historyFile, data, 0644)).To(Succeed())
// This is legacy: we need a config dir in order to have a history dir
filePath = path.Join(os.Getenv("HOME"), ".chatgpt-cli")
Expect(os.MkdirAll(filePath, 0777)).To(Succeed())
Expect(os.Setenv("OPENAI_DATA_HOME", tmpDir)).To(Succeed())
})
it("prints the history for the default thread", func() {
output := runCommand("--show-history")
// Check that the output contains the history as expected
Expect(output).To(ContainSubstring("**USER** 👤:\nHello"))
Expect(output).To(ContainSubstring("**ASSISTANT** 🤖:\nHi, how can I help you?"))
Expect(output).To(ContainSubstring("**USER** 👤:\nTell me about the weather"))
Expect(output).To(ContainSubstring("**ASSISTANT** 🤖:\nIt's sunny today."))
})
it("prints the history for a specific thread when specified", func() {
specificThread := "specific-thread"
specificHistoryFile := filepath.Join(tmpDir, specificThread+".json")
// Create a specific thread with custom history
messages := []types.Message{
{Role: "user", Content: "What's the capital of Belgium?"},
{Role: "assistant", Content: "The capital of Belgium is Brussels."},
}
data, err := json.Marshal(messages)
Expect(err).NotTo(HaveOccurred())
Expect(os.WriteFile(specificHistoryFile, data, 0644)).To(Succeed())
// Run the --show-history flag with the specific thread
output := runCommand("--show-history", specificThread)
// Check that the output contains the history as expected
Expect(output).To(ContainSubstring("**USER** 👤:\nWhat's the capital of Belgium?"))
Expect(output).To(ContainSubstring("**ASSISTANT** 🤖:\nThe capital of Belgium is Brussels."))
})
it("concatenates user messages correctly", func() {
// Create history where two user messages are concatenated
messages := []types.Message{
{Role: "user", Content: "Part one"},
{Role: "user", Content: " and part two"},
{Role: "assistant", Content: "This is a response."},
}
data, err := json.Marshal(messages)
Expect(err).NotTo(HaveOccurred())
Expect(os.WriteFile(historyFile, data, 0644)).To(Succeed())
output := runCommand("--show-history")
// Check that the concatenated user messages are displayed correctly
Expect(output).To(ContainSubstring("**USER** 👤:\nPart one and part two"))
Expect(output).To(ContainSubstring("**ASSISTANT** 🤖:\nThis is a response."))
})
})
})
}