finish handler tests

This commit is contained in:
vinchent 2024-07-16 13:22:46 +02:00
parent 191b010b8e
commit 998850b708
3 changed files with 147 additions and 31 deletions

View File

@ -357,7 +357,7 @@ func (m *Repository) AvailabilityJSON(w http.ResponseWriter, r *http.Request) {
// ChooseRoom displays list of available rooms
func (m *Repository) ChooseRoom(w http.ResponseWriter, r *http.Request) {
exploded := strings.Split(r.RequestURI, "/")
exploded := strings.Split(r.URL.RequestURI(), "/")
roomID, err := strconv.Atoi(exploded[2])
if err != nil {
m.App.Session.Put(r.Context(), "error", "Can't parse roomID")
@ -390,19 +390,19 @@ func (m *Repository) BookRoom(w http.ResponseWriter, r *http.Request) {
layout := "2006-01-02"
startDate, err := time.Parse(layout, sd)
if err != nil {
m.App.Session.Put(r.Context(), "error", "Can't get reservation from session")
m.App.Session.Put(r.Context(), "error", "Can't parse start date")
http.Redirect(w, r, "/availability", http.StatusTemporaryRedirect)
return
}
endDate, err := time.Parse(layout, ed)
if err != nil {
m.App.Session.Put(r.Context(), "error", "Can't parse start date")
m.App.Session.Put(r.Context(), "error", "Can't parse end date")
http.Redirect(w, r, "/availability", http.StatusTemporaryRedirect)
return
}
room, err := m.DB.GetRoomById(roomID)
if err != nil {
m.App.Session.Put(r.Context(), "error", "Can't parse end date")
m.App.Session.Put(r.Context(), "error", "Can't parse roomId")
http.Redirect(w, r, "/availability", http.StatusTemporaryRedirect)
return
}

View File

@ -3,11 +3,13 @@ package handlers
import (
"context"
"encoding/json"
"go-udemy-web-1/internal/driver"
"go-udemy-web-1/internal/models"
"log"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strconv"
"strings"
"testing"
@ -19,6 +21,20 @@ type postData struct {
value string
}
// {{{ Test NewRepo
func Test_NewRepo(t *testing.T) {
var db driver.DB
repo := NewRepo(&app, &db)
if reflect.TypeOf(repo).String() != "*handlers.Repository" {
t.Errorf("repo is of type %s instead of *handlers.Repository", reflect.TypeOf(repo).String())
}
}
// }}}
// {{{ Simple get tests
var theTests = []struct {
name string
url string
@ -31,21 +47,6 @@ var theTests = []struct {
{"ms", "/majors-suite", "GET", http.StatusOK},
{"sa", "/availability", "GET", http.StatusOK},
{"contact", "/contact", "GET", http.StatusOK},
// {"post-search-avail", "/availability", "POST", []postData{
// {key: "start", value: "2020-01-01"},
// {key: "end", value: "2020-01-02"},
// }, http.StatusOK},
// {"post-search-avail-json", "/availability-json", "POST", []postData{
// {key: "start", value: "2020-01-01"},
// {key: "end", value: "2020-01-02"},
// }, http.StatusOK},
// {"make-reservation", "/make-reservation", "POST", []postData{
// {key: "first_name", value: "John"},
// {key: "last_name", value: "Smith"},
// {key: "email", value: "me@here.com"},
// {key: "phone", value: "12345"},
// }, http.StatusOK},
}
func TestHandlers(t *testing.T) {
@ -65,6 +66,7 @@ func TestHandlers(t *testing.T) {
}
}
// }}}
// {{{ Make Reservation Tests
var makeReservationTests = []struct {
@ -141,7 +143,7 @@ var postMakeReservationTests = []struct {
},
http.StatusTemporaryRedirect,
},
{"no_post_data", []postData{}, http.StatusOK},
{"no_post_data", []postData{}, http.StatusTemporaryRedirect},
{
"missing first name",
[]postData{
@ -212,6 +214,7 @@ func TestRepository_PostMakeReservation(t *testing.T) {
for _, test := range postMakeReservationTests {
roomID := 1
reqBody := url.Values{}
var req *http.Request
if len(test.reservationInfo) > 0 {
for _, element := range test.reservationInfo {
reqBody.Add(element.key, element.value)
@ -219,6 +222,9 @@ func TestRepository_PostMakeReservation(t *testing.T) {
roomID, _ = strconv.Atoi(element.value)
}
}
req, _ = http.NewRequest("POST", "/make-reservation", strings.NewReader(reqBody.Encode()))
} else {
req, _ = http.NewRequest("POST", "/make-reservation", nil)
}
layout := "2006-01-02"
sd, _ := time.Parse(layout, "2050-01-01")
@ -229,7 +235,6 @@ func TestRepository_PostMakeReservation(t *testing.T) {
EndDate: ed,
}
req, _ := http.NewRequest("POST", "/make-reservation", strings.NewReader(reqBody.Encode()))
ctx := getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
@ -313,16 +318,25 @@ var availabilityJSONTests = []struct {
OK: false,
Message: "Error connecting to database",
}},
{"no form", []postData{}, jsonResponse{
OK: false,
Message: "Internal server error",
}},
}
func Test_AvailabilityJSON(t *testing.T) {
for _, test := range availabilityJSONTests {
var req *http.Request
reqBody := url.Values{}
for _, element := range test.queryInfo {
reqBody.Add(element.key, element.value)
}
if len(test.queryInfo) > 0 {
for _, element := range test.queryInfo {
reqBody.Add(element.key, element.value)
}
req, _ := http.NewRequest("POST", "/make-reservation", strings.NewReader(reqBody.Encode()))
req, _ = http.NewRequest("POST", "/make-reservation", strings.NewReader(reqBody.Encode()))
} else {
req, _ = http.NewRequest("POST", "/make-reservation", nil)
}
ctx := getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
@ -425,16 +439,22 @@ var postAvailabilityTests = []struct {
{key: "start", value: "2050-01-05"},
{key: "end", value: "01-06"},
}, http.StatusTemporaryRedirect},
{"wrong end date", []postData{}, http.StatusTemporaryRedirect},
}
func Test_PostAvailability(t *testing.T) {
for _, test := range postAvailabilityTests {
reqBody := url.Values{}
for _, element := range test.queryInfo {
reqBody.Add(element.key, element.value)
}
var req *http.Request
if len(test.queryInfo) > 0 {
reqBody := url.Values{}
for _, element := range test.queryInfo {
reqBody.Add(element.key, element.value)
}
req, _ := http.NewRequest("POST", "/availability", strings.NewReader(reqBody.Encode()))
req, _ = http.NewRequest("POST", "/availability", strings.NewReader(reqBody.Encode()))
} else {
req, _ = http.NewRequest("POST", "/availability", nil)
}
ctx := getCtx(req)
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
@ -451,6 +471,102 @@ func Test_PostAvailability(t *testing.T) {
}
}
// }}}
// {{{ Test ChooseRoom
var chooseRoomTests = []struct {
name string
request string
haveSession bool
expectedStatusCode int
}{
{"ok", "/choose-room/1", true, http.StatusSeeOther},
{"wrong room id", "/choose-room/1wrong", true, http.StatusTemporaryRedirect},
{"no session", "/choose-room/1", false, http.StatusTemporaryRedirect},
}
func Test_ChooseRoom(t *testing.T) {
for _, test := range chooseRoomTests {
req, _ := http.NewRequest("GET", test.request, nil)
ctx := getCtx(req)
req = req.WithContext(ctx)
layout := "2006-01-02"
sd, _ := time.Parse(layout, "2050-01-01")
ed, _ := time.Parse(layout, "2050-01-02")
reservation := models.Reservation{
StartDate: sd,
EndDate: ed,
}
if test.haveSession {
session.Put(req.Context(), "reservation", reservation)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(Repo.ChooseRoom)
handler.ServeHTTP(rr, req)
if rr.Code != test.expectedStatusCode {
t.Errorf("for %s, reservation handler returned response code: got %d, wanted %d\n",
test.name, rr.Code, test.expectedStatusCode)
}
}
}
// }}}
// {{{ Test BookRoom
var bookRoomTests = []struct {
name string
queryInfo []postData
expectedStatusCode int
}{
{"ok", []postData{
{key: "id", value: "1"},
{key: "s", value: "2050-01-01"},
{key: "e", value: "2050-01-02"},
}, http.StatusSeeOther},
{"wrong start date", []postData{
{key: "id", value: "1"},
{key: "s", value: "20-01-01"},
{key: "e", value: "2050-01-02"},
}, http.StatusTemporaryRedirect},
{"wrong end date", []postData{
{key: "id", value: "1"},
{key: "s", value: "2050-01-01"},
{key: "e", value: "2050-0-02"},
}, http.StatusTemporaryRedirect},
{"wrong room id", []postData{
{key: "id", value: "w"},
{key: "s", value: "2050-01-01"},
{key: "e", value: "2050-01-02"},
}, http.StatusTemporaryRedirect},
}
func Test_BookRoom(t *testing.T) {
for _, test := range bookRoomTests {
request := "/book-room?"
for _, element := range test.queryInfo {
request += element.key + "=" + element.value + "&"
}
request = request[:len(request)-1]
req, _ := http.NewRequest("GET", request, nil)
ctx := getCtx(req)
req = req.WithContext(ctx)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(Repo.BookRoom)
handler.ServeHTTP(rr, req)
if rr.Code != test.expectedStatusCode {
t.Errorf("for %s, reservation handler returned response code: got %d, wanted %d\n",
test.name, rr.Code, test.expectedStatusCode)
}
}
}
// }}}
// {{{ Test Helpers

View File

@ -59,7 +59,7 @@ func (m *testDBRepo) SearchAvailabilityForAllRooms(start, end time.Time) ([]mode
func (m *testDBRepo) GetRoomById(id int) (models.Room, error) {
var room models.Room
if id > 2 {
if id > 2 || id <= 0 {
return room, errors.New("deliberate error")
}
return room, nil