| 650 | } |
| 651 | |
| 652 | func TestGroup_FileFS(t *testing.T) { |
| 653 | var testCases = []struct { |
| 654 | whenFS fs.FS |
| 655 | name string |
| 656 | whenPath string |
| 657 | whenFile string |
| 658 | givenURL string |
| 659 | expectStartsWith []byte |
| 660 | expectCode int |
| 661 | }{ |
| 662 | { |
| 663 | name: "ok", |
| 664 | whenPath: "/walle", |
| 665 | whenFS: os.DirFS("_fixture/images"), |
| 666 | whenFile: "walle.png", |
| 667 | givenURL: "/assets/walle", |
| 668 | expectCode: http.StatusOK, |
| 669 | expectStartsWith: []byte{0x89, 0x50, 0x4e}, |
| 670 | }, |
| 671 | { |
| 672 | name: "nok, requesting invalid path", |
| 673 | whenPath: "/walle", |
| 674 | whenFS: os.DirFS("_fixture/images"), |
| 675 | whenFile: "walle.png", |
| 676 | givenURL: "/assets/walle.png", |
| 677 | expectCode: http.StatusNotFound, |
| 678 | expectStartsWith: []byte(`{"message":"Not Found"}`), |
| 679 | }, |
| 680 | { |
| 681 | name: "nok, serving not existent file from filesystem", |
| 682 | whenPath: "/walle", |
| 683 | whenFS: os.DirFS("_fixture/images"), |
| 684 | whenFile: "not-existent.png", |
| 685 | givenURL: "/assets/walle", |
| 686 | expectCode: http.StatusNotFound, |
| 687 | expectStartsWith: []byte(`{"message":"Not Found"}`), |
| 688 | }, |
| 689 | } |
| 690 | |
| 691 | for _, tc := range testCases { |
| 692 | t.Run(tc.name, func(t *testing.T) { |
| 693 | e := New() |
| 694 | g := e.Group("/assets") |
| 695 | g.FileFS(tc.whenPath, tc.whenFile, tc.whenFS) |
| 696 | |
| 697 | req := httptest.NewRequest(http.MethodGet, tc.givenURL, nil) |
| 698 | rec := httptest.NewRecorder() |
| 699 | |
| 700 | e.ServeHTTP(rec, req) |
| 701 | |
| 702 | assert.Equal(t, tc.expectCode, rec.Code) |
| 703 | |
| 704 | body := rec.Body.Bytes() |
| 705 | if len(body) > len(tc.expectStartsWith) { |
| 706 | body = body[:len(tc.expectStartsWith)] |
| 707 | } |
| 708 | assert.Equal(t, tc.expectStartsWith, body) |
| 709 | }) |