go-chatgpt
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

47 lines
1.1 KiB

  1. package test
  2. import (
  3. "log"
  4. "net/http"
  5. "net/http/httptest"
  6. )
  7. const testAPI = "this-is-my-secure-token-do-not-steal!!"
  8. func GetTestToken() string {
  9. return testAPI
  10. }
  11. type ServerTest struct {
  12. handlers map[string]handler
  13. }
  14. type handler func(w http.ResponseWriter, r *http.Request)
  15. func NewTestServer() *ServerTest {
  16. return &ServerTest{handlers: make(map[string]handler)}
  17. }
  18. func (ts *ServerTest) RegisterHandler(path string, handler handler) {
  19. ts.handlers[path] = handler
  20. }
  21. // OpenAITestServer Creates a mocked OpenAI server which can pretend to handle requests during testing.
  22. func (ts *ServerTest) OpenAITestServer() *httptest.Server {
  23. return httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  24. log.Printf("received request at path %q\n", r.URL.Path)
  25. // check auth
  26. if r.Header.Get("Authorization") != "Bearer "+GetTestToken() {
  27. w.WriteHeader(http.StatusUnauthorized)
  28. return
  29. }
  30. handlerCall, ok := ts.handlers[r.URL.Path]
  31. if !ok {
  32. http.Error(w, "the resource path doesn't exist", http.StatusNotFound)
  33. return
  34. }
  35. handlerCall(w, r)
  36. }))
  37. }