Skip to content

Commit

Permalink
Add test for HandleHTTPError (#278)
Browse files Browse the repository at this point in the history
* add test for HandleHTTPError

undelete

* more verbose http codes

* Update Dockerfile

Now using go 1.23! Tested this on dev, it works

* Update compose_dev.sh

Prints initial settings as defined in setup.yaml. Added for usability reasons - users keep getting confused about account balance and maximum allowable debt

* add failure condition test

* formatting and test standards

---------

Co-authored-by: Osnat Katz Moon <137817983+astrosnat@users.noreply.github.com>
  • Loading branch information
j4qfrost and astrosnat authored Aug 28, 2024
1 parent e5a74d0 commit fb0b56a
Show file tree
Hide file tree
Showing 6 changed files with 94 additions and 18 deletions.
2 changes: 1 addition & 1 deletion backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# syntax=docker/dockerfile:1.3-labs
FROM golang:1.22.5-bookworm
FROM golang:1.23-bookworm

SHELL ["/bin/bash", "-euo", "pipefail", "-c"]

Expand Down
67 changes: 67 additions & 0 deletions backend/errors/httperror_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package errors

import (
"bytes"
"errors"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

func TestHandleHTTPError(t *testing.T) {
tests := []struct {
name string
w *httptest.ResponseRecorder
err error
statusCode int
userMessage string
output string
wrappedMessage string
res bool
}{
{
name: "Nil",
w: httptest.NewRecorder(),
err: nil,
statusCode: http.StatusOK,
userMessage: "",
output: "",
wrappedMessage: "",
res: false,
},
{
name: "Server Error 500",
w: httptest.NewRecorder(),
err: errors.New("foo"),
statusCode: http.StatusInternalServerError,
userMessage: "bar",
output: "Error: foo",
wrappedMessage: "{\"error\":\"bar\"}",
res: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
currentWriter := log.Writer()
var buf bytes.Buffer
log.SetOutput(&buf)
res := HandleHTTPError(test.w, test.err, test.statusCode, test.userMessage)
log.SetOutput(currentWriter)
if test.res != res {
t.Errorf("got %t, want %t", test.res, res)
}
if test.w.Code != test.statusCode {
t.Errorf("got %d, want %d", test.statusCode, test.w.Code)
}
if !strings.Contains(test.w.Body.String(), test.wrappedMessage) {
t.Errorf("got %s, want %s", strings.TrimRight(test.w.Body.String(), "\n"), test.wrappedMessage)
}
if !strings.Contains(buf.String(), test.output) {
t.Errorf("got Error%s, want %s", strings.SplitN(strings.TrimRight(buf.String(), "\n"), "Error", 1)[0], test.output)
}
})

}
}
23 changes: 12 additions & 11 deletions backend/handlers/setup/setuphandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@ import (
"socialpredict/setup"
)

func GetSetupHandler(w http.ResponseWriter, r *http.Request) {
func GetSetupHandler(loadEconomicsConfig func() (*setup.EconomicConfig, error)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
appConfig, err := loadEconomicsConfig()
if err != nil {
http.Error(w, "Failed to load economic config", http.StatusInternalServerError)
return
}

appConfig, err := setup.LoadEconomicsConfig()
if err != nil {
http.Error(w, "Failed to load economic config", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(appConfig.Economics)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(appConfig.Economics)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
}
15 changes: 10 additions & 5 deletions backend/handlers/setup/setuphandler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
"testing"
)

var loadEconomicsConfig = setup.LoadEconomicsConfig

func TestGetSetupHandler(t *testing.T) {
tests := []struct {
Name string
Expand All @@ -31,22 +29,29 @@ func TestGetSetupHandler(t *testing.T) {
"User":{"InitialAccountBalance":0,"MaximumDebtAllowed":500},
"Betting":{"MinimumBet":1,"BetFees":{"InitialBetFee":1,"EachBetFee":0,"SellSharesFee":0}}}`,
IsJSONResponse: true,
}, {
Name: "failed to load config",
MockConfigLoader: func() (*setup.EconomicConfig, error) {
return nil, http.ErrBodyNotAllowed
},
ExpectedStatus: http.StatusInternalServerError,
ExpectedResponse: "Failed to load economic config",
IsJSONResponse: false,
},
}

for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
// Replace the actual loader function with the mock
loadEconomicsConfig = test.MockConfigLoader
defer func() { loadEconomicsConfig = setup.LoadEconomicsConfig }()
loadEconomicsConfig := test.MockConfigLoader

req, err := http.NewRequest("GET", "/setup", nil)
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()
handler := http.HandlerFunc(GetSetupHandler)
handler := http.HandlerFunc(GetSetupHandler(loadEconomicsConfig))

handler.ServeHTTP(rr, req)

Expand Down
3 changes: 2 additions & 1 deletion backend/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
setuphandlers "socialpredict/handlers/setup"
usershandlers "socialpredict/handlers/users"
"socialpredict/middleware"
"socialpredict/setup"

"github.com/gorilla/mux"
"github.com/rs/cors"
Expand All @@ -36,7 +37,7 @@ func Start() {
router.HandleFunc("/v0/login", middleware.LoginHandler)

// application setup information
router.HandleFunc("/v0/setup", setuphandlers.GetSetupHandler).Methods("GET")
router.HandleFunc("/v0/setup", setuphandlers.GetSetupHandler(setup.LoadEconomicsConfig)).Methods("GET")
// markets display, market information
router.HandleFunc("/v0/markets", marketshandlers.ListMarketsHandler).Methods("GET")
router.HandleFunc("/v0/markets/{marketId}", marketshandlers.MarketDetailsHandler).Methods("GET")
Expand Down
2 changes: 2 additions & 0 deletions scripts/dev/compose_dev.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
if [ "$1" = "up" ]; then
docker compose --env-file $ENV_PATH --file "$SCRIPT_DIR/scripts/docker-compose-dev.yaml" up -d && \
echo "SocialPredict may be found at http://localhost . This may take a few seconds to load initially."
echo "Here are the initial settings. These can be changed in setup.yaml"
cat $SCRIPT_DIR/backend/setup/setup.yaml
elif [ "$1" = "down" ]; then
docker compose --env-file $ENV_PATH --file "$SCRIPT_DIR/scripts/docker-compose-dev.yaml" down
else
Expand Down

0 comments on commit fb0b56a

Please sign in to comment.