From 68000a0f0a5ca2e04ca7cfc0c8050bbd4c89fa3b Mon Sep 17 00:00:00 2001 From: tom Date: Thu, 17 Jul 2025 19:28:21 +0200 Subject: [PATCH] cleanup/small refactor + first tests --- Backend/endpoints/team.go | 49 +---------------------------- Backend/endpoints/time-create.go | 13 ++++---- Backend/endpoints/time.go | 12 ++++---- Backend/helper/system_test.go | 53 ++++++++++++++++++++++++++++++++ Backend/helper/time.go | 16 ++++++++++ Backend/helper/time_test.go | 17 ++++++++++ 6 files changed, 99 insertions(+), 61 deletions(-) create mode 100644 Backend/helper/system_test.go create mode 100644 Backend/helper/time.go create mode 100644 Backend/helper/time_test.go diff --git a/Backend/endpoints/team.go b/Backend/endpoints/team.go index c28cc72..9b214ea 100644 --- a/Backend/endpoints/team.go +++ b/Backend/endpoints/team.go @@ -25,18 +25,6 @@ func TeamHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, "Method not allowed!", http.StatusMethodNotAllowed) break } - // user, err := (*models.User).GetUserFromSession(nil, Session, r.Context()) - // if err != nil { - // log.Println("No user found with the given personal number!") - // http.Redirect(w, r, "/user/login", http.StatusSeeOther) - // return - // } - // var userWorkDays []models.WorkDay - // userWorkDays = (*models.WorkDay).GetWorkDays(nil, user.CardUID, time.Date(2025, time.February, 24, 0, 0, 0, 0, time.Local), time.Date(2025, time.February, 24+7, 0, 0, 0, 0, time.Local)) - // log.Println("User:", user) - // teamMembers, err := user.GetTeamMembers() - // getWeeksTillNow(time.Now().AddDate(0, 0, -14)) - // templates.TeamPage(teamMembers, userWorkDays).Render(r.Context(), w) } func submitReport(w http.ResponseWriter, r *http.Request) { @@ -84,7 +72,7 @@ func showWeeks(w http.ResponseWriter, r *http.Request) { if submissionDate != "" { submissionDate, err := time.Parse("2006-01-02", submissionDate) if err == nil { - lastSub = getMonday(submissionDate) + lastSub = helper.GetMonday(submissionDate) } } userWeek := (*models.WorkWeek).GetWeek(nil, user, lastSub, true) @@ -98,38 +86,3 @@ func showWeeks(w http.ResponseWriter, r *http.Request) { // isRunningWeek := time.Since(lastSub) < 24*5*time.Hour //the last submission is this week and cannot be send yet templates.TeamPage(workWeeks, userWeek).Render(r.Context(), w) } - -func getWeeksTillNow(lastWeek time.Time) []time.Time { - var weeks []time.Time - if lastWeek.After(time.Now()) { - log.Println("Timestamp is after today, no weeks till now!") - return weeks - } - if lastWeek.Weekday() != time.Monday { - if lastWeek.Weekday() == time.Sunday { - lastWeek = lastWeek.AddDate(0, 0, -6) - } else { - lastWeek = lastWeek.AddDate(0, 0, -int(lastWeek.Weekday()-1)) - } - } - if time.Since(lastWeek) < 24*5*time.Hour { - log.Println("Timestamp in running week, cannot split!") - } - - for t := lastWeek; t.Before(time.Now()); t = t.Add(7 * 24 * time.Hour) { - weeks = append(weeks, t) - } - log.Println(weeks) - return weeks -} - -func getMonday(ts time.Time) time.Time { - if ts.Weekday() != time.Monday { - if ts.Weekday() == time.Sunday { - ts = ts.AddDate(0, 0, -6) - } else { - ts = ts.AddDate(0, 0, -int(ts.Weekday()-1)) - } - } - return ts -} diff --git a/Backend/endpoints/time-create.go b/Backend/endpoints/time-create.go index ddeb0a4..7dd0e29 100644 --- a/Backend/endpoints/time-create.go +++ b/Backend/endpoints/time-create.go @@ -33,7 +33,7 @@ func TimeCreateHandler(w http.ResponseWriter, r *http.Request) { // Creates a booking from the http query params -> no body needed // after that entry wi'll be written to database and the booking is returned as json func createBooking(w http.ResponseWriter, r *http.Request) { - if !checkPassword(r) { + if !verifyToken(r) { log.Println("Wrong or no API key provided!") http.Error(w, "Wrong or no API key provided", http.StatusUnauthorized) return @@ -58,16 +58,15 @@ func createBooking(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) } -func checkPassword(r *http.Request) bool { +func verifyToken(r *http.Request) bool { authToken := helper.GetEnv("API_TOKEN", "dont_access") authHeaders := r.Header.Get("Authorization") - _authStart := len("Bearer ") - if len(authHeaders) <= _authStart { + if len(authHeaders) <= 7 { //len "Bearer " authHeaders = r.URL.Query().Get("api_key") - _authStart = 0 - if len(authHeaders) <= _authStart { + if len(authHeaders) <= 0 { return false } + return authToken == authHeaders } - return authToken == authHeaders[_authStart:] + return authToken == authHeaders[7:] } diff --git a/Backend/endpoints/time.go b/Backend/endpoints/time.go index 36abc91..3179995 100644 --- a/Backend/endpoints/time.go +++ b/Backend/endpoints/time.go @@ -34,16 +34,16 @@ func TimeHandler(w http.ResponseWriter, r *http.Request) { } } -func parseTimestamp(r *http.Request, get_key string, fallback string) (time.Time, error) { - _timestamp_get := r.URL.Query().Get(get_key) - if _timestamp_get == "" { - _timestamp_get = fallback +func parseTimestamp(r *http.Request, getKey string, fallback string) (time.Time, error) { + getTimestamp := r.URL.Query().Get(getKey) + if getTimestamp == "" { + getTimestamp = fallback } - timestamp_get, err := time.Parse("2006-01-02", _timestamp_get) + Timestamp, err := time.Parse("2006-01-02", getTimestamp) if err != nil { return time.Now(), err } - return timestamp_get, nil + return Timestamp, nil } // Returns bookings from DB with similar card uid -> checks for card uid in http query params diff --git a/Backend/helper/system_test.go b/Backend/helper/system_test.go new file mode 100644 index 0000000..dc944d9 --- /dev/null +++ b/Backend/helper/system_test.go @@ -0,0 +1,53 @@ +package helper + +import ( + "os" + "testing" + "time" +) + +func TestGetEnv(t *testing.T) { + os.Setenv("GO_TEST_VALUE", "123") + env := GetEnv("GO_TEST_VALUE", "") + if env != "123" { + t.Error("GetEnv() cannot find value") + } +} + +func TestGetEnvEmpty(t *testing.T) { + env := GetEnv("GO_TEST_NOVALUE", "123") + if env != "123" { + t.Errorf("GetEnv() did not use default value: want=%s got=%s", "123", env) + } +} + +func TestCacheCreate(t *testing.T) { + cacheFetch := func(key string) (any, error) { + return "123", nil + } + + cache := NewCache(1*time.Second, cacheFetch) + if cache.ttl != 1*time.Second { + t.Error("Error creating cache") + } +} + +func TestCacheFunction(t *testing.T) { + counter := 1 + cacheFetch := func(key string) (any, error) { + counter += 1 + return counter, nil + } + + cache := NewCache(1*time.Millisecond, cacheFetch) + valInit, err := cache.Get("TEST") + valCache, err := cache.Get("TEST") + time.Sleep(1 * time.Millisecond) + valNoCache, err := cache.Get("TEST") + if err != nil { + t.Errorf("Error getting key from Cache: %e", err) + } + if valInit != valCache || valCache != 2 || valNoCache != 3 { + t.Error("Caching does not resprect ttl.") + } +} diff --git a/Backend/helper/time.go b/Backend/helper/time.go new file mode 100644 index 0000000..5abd82c --- /dev/null +++ b/Backend/helper/time.go @@ -0,0 +1,16 @@ +package helper + +import ( + "time" +) + +func GetMonday(ts time.Time) time.Time { + if ts.Weekday() != time.Monday { + if ts.Weekday() == time.Sunday { + return ts.AddDate(0, 0, -6) + } else { + return ts.AddDate(0, 0, -int(ts.Weekday()-1)) + } + } + return ts +} diff --git a/Backend/helper/time_test.go b/Backend/helper/time_test.go new file mode 100644 index 0000000..c82c4c4 --- /dev/null +++ b/Backend/helper/time_test.go @@ -0,0 +1,17 @@ +package helper + +import ( + "testing" + "time" +) + +func TestGetMonday(t *testing.T) { + isMonday, err := time.Parse("2006-01-02", "2025-07-14") + notMonday, err := time.Parse("2006-01-02", "2025-07-16") + if err != nil || isMonday == notMonday { + t.Errorf("U stupid? %e", err) + } + if GetMonday(isMonday) != isMonday || GetMonday(notMonday) != isMonday { + t.Error("Wrong date conversion!") + } +}