github.com/fragmenta/fragmenta-cms@v1.5.5/src/app/app_test.go (about) 1 package app 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "os" 7 "testing" 8 9 "github.com/fragmenta/auth/can" 10 "github.com/fragmenta/server/config" 11 12 "github.com/fragmenta/fragmenta-cms/src/pages" 13 "github.com/fragmenta/fragmenta-cms/src/users" 14 ) 15 16 // TestRouter tests our routes are functioning correctly. 17 func TestRouter(t *testing.T) { 18 19 // chdir into the root to load config/assets to test this code 20 err := os.Chdir("../../") 21 if err != nil { 22 t.Errorf("Chdir error: %s", err) 23 } 24 25 c := config.New() 26 c.Load("secrets/fragmenta.json") 27 c.Mode = config.ModeTest 28 config.Current = c 29 30 // First, set up the logger 31 err = SetupLog() 32 if err != nil { 33 t.Fatalf("app: failed to set up log %s", err) 34 } 35 36 // Set up our assets 37 SetupAssets() 38 39 // Setup our view templates 40 SetupView() 41 42 // Setup our database 43 SetupDatabase() 44 45 // Set up auth pkg and authorisation for access 46 SetupAuth() 47 48 // Setup our router and handlers 49 router := SetupRoutes() 50 51 // Insert a page at / in the test db 52 pageParams := map[string]string{"url": "/", "name": "test"} 53 _, err = pages.New().Create(pageParams) 54 if err != nil { 55 t.Fatalf("app: failed to create page") 56 } 57 58 // Test serving the route / which should always exist 59 r := httptest.NewRequest("GET", "/", nil) 60 w := httptest.NewRecorder() 61 router.ServeHTTP(w, r) 62 63 // Test code on response 64 if w.Code != http.StatusOK { 65 t.Fatalf("app: error code on / expected:%d got:%d", http.StatusOK, w.Code) 66 } 67 68 } 69 70 // TestAuth tests our authentication is functioning after setup. 71 func TestAuth(t *testing.T) { 72 73 SetupAuth() 74 75 user := &users.User{} 76 77 // Test anon cannot access /users 78 err := can.List(user, users.MockAnon()) 79 if err == nil { 80 t.Fatalf("app: authentication block failed for anon") 81 } 82 83 // Test anon cannot edit admin user 84 err = can.Update(users.MockAdmin(), users.MockAnon()) 85 if err == nil { 86 t.Fatalf("app: authentication block failed for anon") 87 } 88 89 // Test admin can access /users 90 err = can.List(user, users.MockAdmin()) 91 if err != nil { 92 t.Fatalf("app: authentication failed for admin") 93 } 94 95 // Test admin can admin user 96 err = can.Manage(user, users.MockAdmin()) 97 if err != nil { 98 t.Fatalf("app: authentication failed for admin") 99 } 100 101 }