github.com/grafviktor/keep-my-secret@v0.9.10-0.20230908165355-19f35cce90e5/internal/api/web/handler_static_test.go (about) 1 package web 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "os" 7 "strings" 8 "testing" 9 10 "github.com/go-chi/chi/v5" 11 "github.com/stretchr/testify/assert" 12 13 "github.com/grafviktor/keep-my-secret/internal/config" 14 ) 15 16 func TestRegisterStaticHandler(t *testing.T) { 17 // Create a new chi router for testing. 18 serveDir = "./ui" 19 r := chi.NewRouter() 20 21 webAppUrls := []string{"/valid/", "/missing_ending_slash", "" /*empty*/} 22 23 for _, url := range webAppUrls { 24 // Define a test AppConfig. 25 testConfig := config.AppConfig{ 26 ClientAppURL: url, 27 } 28 29 // Register the static handler. 30 registerStaticHandler(testConfig, r) 31 32 // Create a test request for the root URL. 33 req := httptest.NewRequest("GET", "/", nil) 34 w := httptest.NewRecorder() 35 36 // Execute the request. 37 r.ServeHTTP(w, req) 38 39 if !strings.HasSuffix(url, "/") { 40 url += "/" 41 } 42 43 // I know that this file exists in project_root/ui/.keep 44 filePath := url + ".keep" 45 req = httptest.NewRequest("GET", filePath, nil) 46 w = httptest.NewRecorder() 47 48 // Execute the request. 49 r.ServeHTTP(w, req) 50 51 // Check the response status code. It should be StatusOK if the file exists. 52 assert.Equal(t, http.StatusOK, w.Code) 53 54 // Create a test request for a non-existent file. 55 nonExistentFilePath := "/static/non_existent_file.txt" 56 req = httptest.NewRequest("GET", nonExistentFilePath, nil) 57 w = httptest.NewRecorder() 58 59 // Execute the request. 60 r.ServeHTTP(w, req) 61 62 // Check the response status code. It should be StatusNotFound. 63 assert.Equal(t, http.StatusNotFound, w.Code) 64 } 65 } 66 67 func init() { 68 projectRoot := "../../../" 69 err := os.Chdir(projectRoot) 70 if err != nil { 71 panic(err) 72 } 73 }