github.com/saadullahsaeed/fragmenta-cms@v1.5.4/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/users"
    13  )
    14  
    15  // TestRouter tests our routes are functioning correctly.
    16  func TestRouter(t *testing.T) {
    17  
    18  	// chdir into the root to load config/assets to test this code
    19  	err := os.Chdir("../../")
    20  	if err != nil {
    21  		t.Errorf("Chdir error: %s", err)
    22  	}
    23  
    24  	c := config.New()
    25  	c.Load("secrets/fragmenta.json")
    26  	c.Mode = config.ModeTest
    27  	config.Current = c
    28  
    29  	// First, set up the logger
    30  	err = SetupLog()
    31  	if err != nil {
    32  		t.Fatalf("app: failed to set up log %s", err)
    33  	}
    34  
    35  	// Set up our assets
    36  	SetupAssets()
    37  
    38  	// Setup our view templates
    39  	SetupView()
    40  
    41  	// Setup our database
    42  	SetupDatabase()
    43  
    44  	// Set up auth pkg and authorisation for access
    45  	SetupAuth()
    46  
    47  	// Setup our router and handlers
    48  	router := SetupRoutes()
    49  
    50  	// Test serving the route / which should always exist
    51  	r := httptest.NewRequest("GET", "/", nil)
    52  	w := httptest.NewRecorder()
    53  	router.ServeHTTP(w, r)
    54  
    55  	// Test code on response
    56  	if w.Code != http.StatusOK {
    57  		t.Fatalf("app: error code on / expected:%d got:%d", http.StatusOK, w.Code)
    58  	}
    59  
    60  }
    61  
    62  // TestAuth tests our authentication is functioning after setup.
    63  func TestAuth(t *testing.T) {
    64  
    65  	SetupAuth()
    66  
    67  	user := &users.User{}
    68  
    69  	// Test anon cannot access /users
    70  	err := can.List(user, users.MockAnon())
    71  	if err == nil {
    72  		t.Fatalf("app: authentication block failed for anon")
    73  	}
    74  
    75  	// Test anon cannot edit admin user
    76  	err = can.Update(users.MockAdmin(), users.MockAnon())
    77  	if err == nil {
    78  		t.Fatalf("app: authentication block failed for anon")
    79  	}
    80  
    81  	// Test admin can access /users
    82  	err = can.List(user, users.MockAdmin())
    83  	if err != nil {
    84  		t.Fatalf("app: authentication failed for admin")
    85  	}
    86  
    87  	// Test admin can admin user
    88  	err = can.Manage(user, users.MockAdmin())
    89  	if err != nil {
    90  		t.Fatalf("app: authentication failed for admin")
    91  	}
    92  
    93  }