ascii-live/tests/handlers_test.go
franz.germann 207a7894f7
All checks were successful
ci / build (push) Successful in 44s
fixes some module and package problems
2025-03-28 10:13:30 +01:00

91 lines
2.3 KiB
Go

package test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"ascii-live/handlers"
"github.com/gorilla/mux"
)
func TestListHandler(t *testing.T) {
r := mux.NewRouter()
r.HandleFunc("/ascii-live/list", handlers.ListHandler)
req, err := http.NewRequest("GET", "/ascii-live/list", nil)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
r.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
var response map[string][]string
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Errorf("error decoding response: %v", err)
}
}
func TestNotFoundHandler(t *testing.T) {
r := mux.NewRouter()
req, err := http.NewRequest("GET", "/not-existing", nil)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
r.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusNotFound {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound)
}
}
func TestNotCurledHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/ascii-live/test", nil)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
handler := http.HandlerFunc(handlers.NotCurledHandler)
handler.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusExpectationFailed {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusExpectationFailed)
}
var response map[string]string
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Errorf("error decoding response: %v", err)
}
}
func TestWriteJson(t *testing.T) {
recorder := httptest.NewRecorder()
// req, _ := http.NewRequest("GET", "/", nil)
//testData := map[string]string{"message": "hello"}
// writeJson(recorder, req, testData, http.StatusOK)
if status := recorder.Code; status != http.StatusOK {
t.Errorf("writeJson returned wrong status code: got %v want %v", status, http.StatusOK)
}
var response map[string]string
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Errorf("error decoding response: %v", err)
}
if response["message"] != "hello" {
t.Errorf("writeJson returned unexpected body: got %v want %v", response["message"], "hello")
}
}