controller_test.go

657 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
package application

import (
	"errors"
	"html/template"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"testing/fstest"
)

func TestBaseController_QueryParam_ReturnsValue(t *testing.T) {
	req := httptest.NewRequest("GET", "/test?page=5", nil)
	c := &BaseController{Request: req}

	got := c.QueryParam("page", "1")
	if got != "5" {
		t.Errorf("expected '5', got %q", got)
	}
}

func TestBaseController_QueryParam_ReturnsDefaultWhenEmpty(t *testing.T) {
	req := httptest.NewRequest("GET", "/test", nil)
	c := &BaseController{Request: req}

	got := c.QueryParam("page", "1")
	if got != "1" {
		t.Errorf("expected default '1', got %q", got)
	}
}

func TestBaseController_QueryParam_ReturnsDefaultWhenParamEmpty(t *testing.T) {
	req := httptest.NewRequest("GET", "/test?page=", nil)
	c := &BaseController{Request: req}

	got := c.QueryParam("page", "1")
	if got != "1" {
		t.Errorf("expected default '1' for empty param, got %q", got)
	}
}

func TestBaseController_QueryParam_NilRequest(t *testing.T) {
	c := &BaseController{Request: nil}

	got := c.QueryParam("page", "default")
	if got != "default" {
		t.Errorf("expected 'default' for nil request, got %q", got)
	}
}

func TestBaseController_IntParam_ReturnsInt(t *testing.T) {
	req := httptest.NewRequest("GET", "/test?count=42", nil)
	c := &BaseController{Request: req}

	got := c.IntParam("count", 10)
	if got != 42 {
		t.Errorf("expected 42, got %d", got)
	}
}

func TestBaseController_IntParam_ReturnsDefaultForNonInt(t *testing.T) {
	req := httptest.NewRequest("GET", "/test?count=abc", nil)
	c := &BaseController{Request: req}

	got := c.IntParam("count", 10)
	if got != 10 {
		t.Errorf("expected default 10 for non-int, got %d", got)
	}
}

func TestBaseController_IntParam_ReturnsDefaultForMissing(t *testing.T) {
	req := httptest.NewRequest("GET", "/test", nil)
	c := &BaseController{Request: req}

	got := c.IntParam("count", 99)
	if got != 99 {
		t.Errorf("expected default 99 for missing param, got %d", got)
	}
}

func TestBaseController_IsHTMX_True(t *testing.T) {
	req := httptest.NewRequest("GET", "/test", nil)
	req.Header.Set("HX-Request", "true")
	c := &BaseController{}

	if !c.IsHTMX(req) {
		t.Error("expected IsHTMX to return true")
	}
}

func TestBaseController_IsHTMX_False(t *testing.T) {
	req := httptest.NewRequest("GET", "/test", nil)
	c := &BaseController{}

	if c.IsHTMX(req) {
		t.Error("expected IsHTMX to return false")
	}
}

func TestBaseController_IsHTMX_WrongValue(t *testing.T) {
	req := httptest.NewRequest("GET", "/test", nil)
	req.Header.Set("HX-Request", "false")
	c := &BaseController{}

	if c.IsHTMX(req) {
		t.Error("expected IsHTMX to return false for HX-Request=false")
	}
}

func TestBaseController_Redirect_HTTP(t *testing.T) {
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/old", nil)
	c := &BaseController{}

	c.Redirect(rec, req, "/new")

	if rec.Code != http.StatusSeeOther {
		t.Errorf("expected status 303, got %d", rec.Code)
	}
	location := rec.Header().Get("Location")
	if location != "/new" {
		t.Errorf("expected Location '/new', got %q", location)
	}
}

func TestBaseController_Redirect_HTMX(t *testing.T) {
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/old", nil)
	req.Header.Set("HX-Request", "true")
	c := &BaseController{}

	c.Redirect(rec, req, "/new")

	if rec.Code != http.StatusOK {
		t.Errorf("expected status 200 for HTMX redirect, got %d", rec.Code)
	}
	hxLocation := rec.Header().Get("HX-Location")
	if hxLocation != "/new" {
		t.Errorf("expected HX-Location '/new', got %q", hxLocation)
	}
}

func TestBaseController_Refresh_HTTP(t *testing.T) {
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/current", nil)
	c := &BaseController{}

	c.Refresh(rec, req)

	if rec.Code != http.StatusSeeOther {
		t.Errorf("expected status 303, got %d", rec.Code)
	}
	location := rec.Header().Get("Location")
	if location != "/current" {
		t.Errorf("expected Location '/current', got %q", location)
	}
}

func TestBaseController_Refresh_HTMX(t *testing.T) {
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/current", nil)
	req.Header.Set("HX-Request", "true")
	c := &BaseController{}

	c.Refresh(rec, req)

	if rec.Code != http.StatusOK {
		t.Errorf("expected status 200 for HTMX refresh, got %d", rec.Code)
	}
	hxRefresh := rec.Header().Get("HX-Refresh")
	if hxRefresh != "true" {
		t.Errorf("expected HX-Refresh 'true', got %q", hxRefresh)
	}
}

func TestBaseController_Stream_SetsSSEHeaders(t *testing.T) {
	rec := httptest.NewRecorder()
	c := &BaseController{}

	streamer := c.Stream(rec)

	if streamer == nil {
		t.Fatal("expected non-nil Streamer")
	}

	ct := rec.Header().Get("Content-Type")
	if ct != "text/event-stream" {
		t.Errorf("expected Content-Type 'text/event-stream', got %q", ct)
	}
	cc := rec.Header().Get("Cache-Control")
	if cc != "no-cache" {
		t.Errorf("expected Cache-Control 'no-cache', got %q", cc)
	}
	conn := rec.Header().Get("Connection")
	if conn != "keep-alive" {
		t.Errorf("expected Connection 'keep-alive', got %q", conn)
	}
	xab := rec.Header().Get("X-Accel-Buffering")
	if xab != "no" {
		t.Errorf("expected X-Accel-Buffering 'no', got %q", xab)
	}
}

func TestStreamer_Send(t *testing.T) {
	rec := httptest.NewRecorder()
	s := &Streamer{w: rec, flusher: rec}

	err := s.Send("update", "hello world")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	body := rec.Body.String()
	if !strings.Contains(body, "event: update\n") {
		t.Errorf("expected 'event: update\\n', got: %q", body)
	}
	if !strings.Contains(body, "data: hello world\n") {
		t.Errorf("expected 'data: hello world\\n', got: %q", body)
	}
}

func TestStreamer_Send_MultilineData(t *testing.T) {
	rec := httptest.NewRecorder()
	s := &Streamer{w: rec, flusher: rec}

	err := s.Send("msg", "line1\nline2\nline3")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	body := rec.Body.String()
	// Each line should be prefixed with "data: "
	if !strings.Contains(body, "data: line1\n") {
		t.Errorf("expected 'data: line1\\n', got: %q", body)
	}
	if !strings.Contains(body, "data: line2\n") {
		t.Errorf("expected 'data: line2\\n', got: %q", body)
	}
	if !strings.Contains(body, "data: line3\n") {
		t.Errorf("expected 'data: line3\\n', got: %q", body)
	}
}

func TestStreamer_SendData(t *testing.T) {
	rec := httptest.NewRecorder()
	s := &Streamer{w: rec, flusher: rec}

	err := s.SendData("payload")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	body := rec.Body.String()
	// SendData should not include an event line
	if strings.Contains(body, "event:") {
		t.Errorf("SendData should not include event line, got: %q", body)
	}
	if !strings.Contains(body, "data: payload\n") {
		t.Errorf("expected 'data: payload\\n', got: %q", body)
	}
	// Should end with blank line (SSE message terminator)
	if !strings.HasSuffix(body, "\n\n") {
		t.Errorf("expected message to end with blank line, got: %q", body)
	}
}

func TestStreamer_SendData_NoFlusher(t *testing.T) {
	rec := httptest.NewRecorder()
	// No flusher set
	s := &Streamer{w: rec, flusher: nil}

	err := s.SendData("data")
	if err != nil {
		t.Fatalf("unexpected error without flusher: %v", err)
	}

	body := rec.Body.String()
	if !strings.Contains(body, "data: data\n") {
		t.Errorf("expected data line, got: %q", body)
	}
}

// errorWriter is a writer that always returns an error, for testing error paths.
type errorWriter struct{}

func (errorWriter) Header() http.Header         { return http.Header{} }
func (errorWriter) Write([]byte) (int, error)    { return 0, errors.New("write error") }
func (errorWriter) WriteHeader(int)              {}

func TestStreamer_Send_ErrorOnEventWrite(t *testing.T) {
	ew := errorWriter{}
	s := &Streamer{w: ew, flusher: nil}

	err := s.Send("update", "hello")
	if err == nil {
		t.Fatal("expected error from Send when event write fails")
	}
	if !strings.Contains(err.Error(), "write error") {
		t.Errorf("expected 'write error', got: %v", err)
	}
}

func TestStreamer_Send_ErrorOnDataWrite(t *testing.T) {
	// Writer that succeeds on the event line but fails on data
	w := &failAfterNWriter{limit: 1}
	s := &Streamer{w: w, flusher: nil}

	err := s.Send("update", "hello")
	if err == nil {
		t.Fatal("expected error from Send when data write fails")
	}
}

func TestStreamer_Send_NoFlusher(t *testing.T) {
	rec := httptest.NewRecorder()
	s := &Streamer{w: rec, flusher: nil}

	err := s.Send("evt", "data")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	body := rec.Body.String()
	if !strings.Contains(body, "event: evt\n") {
		t.Errorf("expected event line, got: %q", body)
	}
	if !strings.Contains(body, "data: data\n") {
		t.Errorf("expected data line, got: %q", body)
	}
}

func TestStreamer_SendData_ErrorOnWrite(t *testing.T) {
	ew := errorWriter{}
	s := &Streamer{w: ew, flusher: nil}

	err := s.SendData("data")
	if err == nil {
		t.Fatal("expected error from SendData when write fails")
	}
}

func TestStreamer_WriteData_ErrorOnTerminator(t *testing.T) {
	// Writer that succeeds on data lines but fails on the final "\n" terminator.
	// Single-line data: first write is "data: x\n" (succeeds), second is "\n" (fails).
	w := &failAfterNWriter{limit: 1}
	s := &Streamer{w: w, flusher: nil}

	err := s.writeData("x")
	if err == nil {
		t.Fatal("expected error from writeData when terminator write fails")
	}
}

// failAfterNWriter succeeds on the first N Write calls, then returns an error.
type failAfterNWriter struct {
	limit int
	count int
}

func (f *failAfterNWriter) Header() http.Header { return http.Header{} }
func (f *failAfterNWriter) Write(p []byte) (int, error) {
	f.count++
	if f.count > f.limit {
		return 0, errors.New("write error")
	}
	return len(p), nil
}
func (f *failAfterNWriter) WriteHeader(int) {}

func TestStreamer_Render_Success(t *testing.T) {
	views := fstest.MapFS{
		"views/layouts/base.html":      {Data: []byte(`{{define "base.html"}}base{{end}}`)},
		"views/partials/greeting.html": {Data: []byte(`{{define "greeting.html"}}Hello, {{.}}!{{end}}`)},
	}

	app := New(WithViews(views))

	rec := httptest.NewRecorder()
	s := &Streamer{w: rec, flusher: rec, app: app}

	err := s.Render("greet", "greeting.html", "World")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	body := rec.Body.String()
	if !strings.Contains(body, "event: greet\n") {
		t.Errorf("expected event line, got: %q", body)
	}
	if !strings.Contains(body, "data: Hello, World!") {
		t.Errorf("expected rendered template in data, got: %q", body)
	}
	// Newlines in rendered HTML should be replaced with spaces
	if strings.Contains(body, "data: Hello, World!\n") && strings.Count(body, "\n") > 3 {
		// Actually the rendered template is single-line, so check the structure
	}
}

func TestStreamer_Render_TemplateNotFound(t *testing.T) {
	views := fstest.MapFS{
		"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
	}

	app := New(WithViews(views))

	rec := httptest.NewRecorder()
	s := &Streamer{w: rec, flusher: rec, app: app}

	err := s.Render("greet", "nonexistent.html", nil)
	if err == nil {
		t.Fatal("expected error for nonexistent template")
	}
}

func TestStreamer_Render_WriteError(t *testing.T) {
	views := fstest.MapFS{
		"views/layouts/base.html":      {Data: []byte(`{{define "base.html"}}base{{end}}`)},
		"views/partials/greeting.html": {Data: []byte(`{{define "greeting.html"}}Hi{{end}}`)},
	}

	app := New(WithViews(views))

	ew := errorWriter{}
	s := &Streamer{w: ew, flusher: nil, app: app}

	err := s.Render("greet", "greeting.html", nil)
	if err == nil {
		t.Fatal("expected error when write fails")
	}
}

func TestStreamer_Render_NoFlusher(t *testing.T) {
	views := fstest.MapFS{
		"views/layouts/base.html":      {Data: []byte(`{{define "base.html"}}base{{end}}`)},
		"views/partials/greeting.html": {Data: []byte(`{{define "greeting.html"}}Hi{{end}}`)},
	}

	app := New(WithViews(views))

	rec := httptest.NewRecorder()
	s := &Streamer{w: rec, flusher: nil, app: app}

	err := s.Render("greet", "greeting.html", nil)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	body := rec.Body.String()
	if !strings.Contains(body, "event: greet\n") {
		t.Errorf("expected event line, got: %q", body)
	}
}

func TestStreamer_Render_ReplacesNewlines(t *testing.T) {
	views := fstest.MapFS{
		"views/layouts/base.html":    {Data: []byte(`{{define "base.html"}}base{{end}}`)},
		"views/partials/multi.html":  {Data: []byte("{{define \"multi.html\"}}<div>\n<p>hello</p>\n</div>{{end}}")},
	}

	app := New(WithViews(views))

	rec := httptest.NewRecorder()
	s := &Streamer{w: rec, flusher: rec, app: app}

	err := s.Render("content", "multi.html", nil)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	body := rec.Body.String()
	// The data line should have newlines replaced with spaces
	if strings.Contains(body, "data: <div>\n<p>") {
		t.Errorf("expected newlines in rendered HTML to be replaced with spaces, got: %q", body)
	}
	if !strings.Contains(body, "<div> <p>hello</p> </div>") {
		t.Errorf("expected spaces instead of newlines, got: %q", body)
	}
}

func TestBaseController_Render_DelegatesToApp(t *testing.T) {
	views := fstest.MapFS{
		"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
		"views/test-render.html":  {Data: []byte(`rendered: {{.}}`)},
	}

	app := New(WithViews(views))
	c := &BaseController{App: app}

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/test", nil)

	c.Render(rec, req, "test-render.html", "hello")

	if rec.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d", rec.Code)
	}
	body := rec.Body.String()
	if !strings.Contains(body, "rendered: hello") {
		t.Errorf("expected 'rendered: hello', got: %s", body)
	}
}

func TestBaseController_Stream_WithFlusherResponseWriter(t *testing.T) {
	fr := &flusherRecorder{ResponseRecorder: httptest.NewRecorder()}
	c := &BaseController{}

	streamer := c.Stream(fr)
	if streamer == nil {
		t.Fatal("expected non-nil Streamer")
	}

	// Verify flusher was detected and initial flush happened
	if !fr.flushed {
		t.Error("expected initial Flush call")
	}
}

func TestBaseController_Stream_WithoutFlusher(t *testing.T) {
	nfw := nonFlusherWriter{httptest.NewRecorder()}
	c := &BaseController{}

	streamer := c.Stream(nfw)
	if streamer == nil {
		t.Fatal("expected non-nil Streamer")
	}
	// Should not panic when underlying writer does not implement Flusher
}

func TestApp_Method_ValidMethod(t *testing.T) {
	app := New()
	c := &methodTestController{}

	handler := app.Method(c, "Greet", nil)

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/greet", nil)
	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d", rec.Code)
	}
	body := rec.Body.String()
	if body != "hello" {
		t.Errorf("expected 'hello', got %q", body)
	}
}

type methodTestController struct{}

func (c *methodTestController) Greet(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello"))
}

func TestApp_Method_WithBouncerAllows(t *testing.T) {
	app := New()
	c := &methodTestController{}

	allower := func(app *App, w http.ResponseWriter, r *http.Request) bool {
		return true
	}

	handler := app.Method(c, "Greet", allower)

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/greet", nil)
	handler.ServeHTTP(rec, req)

	body := rec.Body.String()
	if body != "hello" {
		t.Errorf("expected 'hello', got %q", body)
	}
}

func TestApp_Method_WithBouncerBlocks(t *testing.T) {
	app := New()
	c := &methodTestController{}

	blocker := func(app *App, w http.ResponseWriter, r *http.Request) bool {
		http.Error(w, "denied", http.StatusForbidden)
		return false
	}

	handler := app.Method(c, "Greet", blocker)

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/greet", nil)
	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusForbidden {
		t.Errorf("expected status 403, got %d", rec.Code)
	}
	body := rec.Body.String()
	if !strings.Contains(body, "denied") {
		t.Errorf("expected 'denied', got %q", body)
	}
}

func TestApp_Render_WithScriptFunc(t *testing.T) {
	views := fstest.MapFS{
		"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
		"views/script-test.html":  {Data: []byte(`script={{frontend_script}}`)},
	}

	app := New(WithViews(views))
	app.ScriptFunc = func(nonce string) template.HTML {
		return template.HTML(`<script nonce="` + nonce + `">app()</script>`)
	}

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/script-test", nil)
	app.render(rec, req, "script-test.html", nil)

	body := rec.Body.String()
	if !strings.Contains(body, "<script") {
		t.Errorf("expected script tag, got: %s", body)
	}
}

func TestApp_Render_WithController(t *testing.T) {
	views := fstest.MapFS{
		"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
		"views/ctrl-test.html":    {Data: []byte(`name={{(home).Name}}`)},
	}

	ctrl := &nameController{name: "Congo"}
	app := New(
		WithController("home", ctrl),
		WithViews(views),
	)

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/ctrl-test", nil)
	app.render(rec, req, "ctrl-test.html", nil)

	body := rec.Body.String()
	if !strings.Contains(body, "name=Congo") {
		t.Errorf("expected 'name=Congo', got: %s", body)
	}
}

type nameController struct {
	BaseController
	name string
}

func (c *nameController) Handle(r *http.Request) Controller {
	return c
}

func (c *nameController) Name() string {
	return c.name
}

func (c *nameController) Setup(app *App) {
	c.BaseController.Setup(app)
}