@@ -45,33 +45,64 @@ func TestStatic_useCaseForApiAndSPAs(t *testing.T) {
4545}
4646
4747func TestStaticHTML5PreservesMatchedHandlerNotFound (t * testing.T ) {
48- e := echo .New ()
49- e .Use (StaticWithConfig (StaticConfig {
50- Root : "testdata/dist/public" ,
51- HTML5 : true ,
52- }))
53- e .GET ("/api/users/:id" , func (c * echo.Context ) error {
54- return echo .NewHTTPError (http .StatusNotFound , "user not found" )
55- })
56-
57- req := httptest .NewRequest (http .MethodGet , "/api/users/42" , nil )
58- rec := httptest .NewRecorder ()
59- e .ServeHTTP (rec , req )
48+ var testCases = []struct {
49+ name string
50+ buildEcho func () * echo.Echo
51+ whenURL string
52+ expectCode int
53+ expectJSONEq string
54+ expectContains string
55+ }{
56+ {
57+ name : "ok, router-matched handler 404 is preserved instead of serving index" ,
58+ buildEcho : func () * echo.Echo {
59+ e := echo .New ()
60+ e .Use (StaticWithConfig (StaticConfig {
61+ Root : "testdata/dist/public" ,
62+ HTML5 : true ,
63+ }))
64+ e .GET ("/api/users/:id" , func (c * echo.Context ) error {
65+ return echo .NewHTTPError (http .StatusNotFound , "user not found" )
66+ })
67+ return e
68+ },
69+ whenURL : "/api/users/42" ,
70+ expectCode : http .StatusNotFound ,
71+ expectJSONEq : `{"message":"user not found"}` ,
72+ },
73+ {
74+ name : "ok, router-level 404 for group without matched route still serves index" ,
75+ buildEcho : func () * echo.Echo {
76+ e := echo .New ()
77+ e .Group ("/app" , StaticWithConfig (StaticConfig {
78+ Root : "testdata/dist/public" ,
79+ HTML5 : true ,
80+ }))
81+ return e
82+ },
83+ whenURL : "/app/dashboard" ,
84+ expectCode : http .StatusOK ,
85+ expectContains : "<h1>Hello from index</h1>\n " ,
86+ },
87+ }
6088
61- assert .Equal (t , http .StatusNotFound , rec .Code )
62- assert .JSONEq (t , `{"message":"user not found"}` , rec .Body .String ())
89+ for _ , tc := range testCases {
90+ t .Run (tc .name , func (t * testing.T ) {
91+ e := tc .buildEcho ()
6392
64- group := echo .New ()
65- group .Group ("/app" , StaticWithConfig (StaticConfig {
66- Root : "testdata/dist/public" ,
67- HTML5 : true ,
68- }))
69- req = httptest .NewRequest (http .MethodGet , "/app/dashboard" , nil )
70- rec = httptest .NewRecorder ()
71- group .ServeHTTP (rec , req )
93+ req := httptest .NewRequest (http .MethodGet , tc .whenURL , nil )
94+ rec := httptest .NewRecorder ()
95+ e .ServeHTTP (rec , req )
7296
73- assert .Equal (t , http .StatusOK , rec .Code )
74- assert .Contains (t , rec .Body .String (), "<h1>Hello from index</h1>\n " )
97+ assert .Equal (t , tc .expectCode , rec .Code )
98+ if tc .expectJSONEq != "" {
99+ assert .JSONEq (t , tc .expectJSONEq , rec .Body .String ())
100+ }
101+ if tc .expectContains != "" {
102+ assert .Contains (t , rec .Body .String (), tc .expectContains )
103+ }
104+ })
105+ }
75106}
76107
77108func TestStatic (t * testing.T ) {
0 commit comments