| 476 | } |
| 477 | |
| 478 | func TestEcho_FileFS(t *testing.T) { |
| 479 | var testCases = []struct { |
| 480 | whenFS fs.FS |
| 481 | name string |
| 482 | whenPath string |
| 483 | whenFile string |
| 484 | givenURL string |
| 485 | expectStartsWith []byte |
| 486 | expectCode int |
| 487 | }{ |
| 488 | { |
| 489 | name: "ok", |
| 490 | whenPath: "/walle", |
| 491 | whenFS: os.DirFS("_fixture/images"), |
| 492 | whenFile: "walle.png", |
| 493 | givenURL: "/walle", |
| 494 | expectCode: http.StatusOK, |
| 495 | expectStartsWith: []byte{0x89, 0x50, 0x4e}, |
| 496 | }, |
| 497 | { |
| 498 | name: "nok, requesting invalid path", |
| 499 | whenPath: "/walle", |
| 500 | whenFS: os.DirFS("_fixture/images"), |
| 501 | whenFile: "walle.png", |
| 502 | givenURL: "/walle.png", |
| 503 | expectCode: http.StatusNotFound, |
| 504 | expectStartsWith: []byte(`{"message":"Not Found"}`), |
| 505 | }, |
| 506 | { |
| 507 | name: "nok, serving not existent file from filesystem", |
| 508 | whenPath: "/walle", |
| 509 | whenFS: os.DirFS("_fixture/images"), |
| 510 | whenFile: "not-existent.png", |
| 511 | givenURL: "/walle", |
| 512 | expectCode: http.StatusNotFound, |
| 513 | expectStartsWith: []byte(`{"message":"Not Found"}`), |
| 514 | }, |
| 515 | } |
| 516 | |
| 517 | for _, tc := range testCases { |
| 518 | t.Run(tc.name, func(t *testing.T) { |
| 519 | e := New() |
| 520 | e.FileFS(tc.whenPath, tc.whenFile, tc.whenFS) |
| 521 | |
| 522 | req := httptest.NewRequest(http.MethodGet, tc.givenURL, nil) |
| 523 | rec := httptest.NewRecorder() |
| 524 | |
| 525 | e.ServeHTTP(rec, req) |
| 526 | |
| 527 | assert.Equal(t, tc.expectCode, rec.Code) |
| 528 | |
| 529 | body := rec.Body.Bytes() |
| 530 | if len(body) > len(tc.expectStartsWith) { |
| 531 | body = body[:len(tc.expectStartsWith)] |
| 532 | } |
| 533 | assert.Equal(t, tc.expectStartsWith, body) |
| 534 | }) |
| 535 | } |