|
| 1 | +package basicauth_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/cloudlena/adapters/basicauth" |
| 10 | +) |
| 11 | + |
| 12 | +func TestHandler(t *testing.T) { |
| 13 | + users := []basicauth.User{ |
| 14 | + {Username: "user", Password: "password"}, |
| 15 | + } |
| 16 | + realm := "My Realm" |
| 17 | + |
| 18 | + tests := []struct { |
| 19 | + name string |
| 20 | + username string |
| 21 | + password string |
| 22 | + expectedStatus int |
| 23 | + expectedBody string |
| 24 | + }{ |
| 25 | + { |
| 26 | + name: "No credentials", |
| 27 | + username: "", |
| 28 | + password: "", |
| 29 | + expectedStatus: http.StatusUnauthorized, |
| 30 | + expectedBody: "Unauthorized\n", |
| 31 | + }, |
| 32 | + { |
| 33 | + name: "Invalid credentials", |
| 34 | + username: "wronguser", |
| 35 | + password: "wrongpass", |
| 36 | + expectedStatus: http.StatusUnauthorized, |
| 37 | + expectedBody: "Unauthorized\n", |
| 38 | + }, |
| 39 | + { |
| 40 | + name: "Valid credentials", |
| 41 | + username: "user", |
| 42 | + password: "password", |
| 43 | + expectedStatus: http.StatusOK, |
| 44 | + expectedBody: "OK", |
| 45 | + }, |
| 46 | + } |
| 47 | + |
| 48 | + for _, tt := range tests { |
| 49 | + t.Run(tt.name, func(t *testing.T) { |
| 50 | + req := httptest.NewRequest(http.MethodGet, "/", nil) |
| 51 | + if tt.username != "" || tt.password != "" { |
| 52 | + req.SetBasicAuth(tt.username, tt.password) |
| 53 | + } |
| 54 | + rr := httptest.NewRecorder() |
| 55 | + |
| 56 | + nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 57 | + _, err := fmt.Fprint(w, "OK") |
| 58 | + if err != nil { |
| 59 | + t.FailNow() |
| 60 | + } |
| 61 | + }) |
| 62 | + |
| 63 | + handler := basicauth.Handler(realm, users)(nextHandler) |
| 64 | + handler.ServeHTTP(rr, req) |
| 65 | + |
| 66 | + if rr.Code != tt.expectedStatus { |
| 67 | + t.Errorf("Expected status %d, got %d", tt.expectedStatus, rr.Code) |
| 68 | + } |
| 69 | + if rr.Body.String() != tt.expectedBody { |
| 70 | + t.Errorf("Expected body %q, got %q", tt.expectedBody, rr.Body.String()) |
| 71 | + } |
| 72 | + }) |
| 73 | + } |
| 74 | +} |
0 commit comments