69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestRenderCounter(t *testing.T) {
|
|
html := renderCounter(7)
|
|
if !strings.Contains(html, "Clicks:") {
|
|
t.Fatalf("expected counter markup to include label")
|
|
}
|
|
if !strings.Contains(html, "> 7<") {
|
|
t.Fatalf("expected counter value in markup, got %q", html)
|
|
}
|
|
}
|
|
|
|
func TestRenderTime(t *testing.T) {
|
|
now := time.Date(2024, time.August, 1, 12, 34, 56, 0, time.UTC)
|
|
html := renderTime(now)
|
|
expected := "2024-08-01 12:34:56"
|
|
if !strings.Contains(html, expected) {
|
|
t.Fatalf("expected formatted timestamp %s in markup", expected)
|
|
}
|
|
}
|
|
|
|
func TestCounterEndpoint(t *testing.T) {
|
|
srv, err := New()
|
|
if err != nil {
|
|
t.Fatalf("failed to create server: %v", err)
|
|
}
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/counter", nil)
|
|
resp := httptest.NewRecorder()
|
|
|
|
srv.Router().ServeHTTP(resp, req)
|
|
|
|
if resp.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d", resp.Code)
|
|
}
|
|
|
|
body := resp.Body.String()
|
|
if !strings.Contains(body, "> 1<") {
|
|
t.Fatalf("expected counter to increment to 1, body: %q", body)
|
|
}
|
|
}
|
|
|
|
func TestNotFound(t *testing.T) {
|
|
srv, err := New()
|
|
if err != nil {
|
|
t.Fatalf("failed to create server: %v", err)
|
|
}
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/unknown", nil)
|
|
resp := httptest.NewRecorder()
|
|
|
|
srv.Router().ServeHTTP(resp, req)
|
|
|
|
if resp.Code != http.StatusNotFound {
|
|
t.Fatalf("expected 404, got %d", resp.Code)
|
|
}
|
|
if !strings.Contains(resp.Body.String(), "Route /unknown not found.") {
|
|
t.Fatalf("expected not found message, got %q", resp.Body.String())
|
|
}
|
|
}
|