github.com/mssola/todo@v0.0.0-20181029153210-d25348dc3f48/app/root_test.go (about)

     1  // Copyright (C) 2014-2017 Miquel Sabaté Solà <mikisabate@gmail.com>
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, v. 2.0. If a copy of the MPL was not distributed with this
     5  // file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  
     7  package app
     8  
     9  import (
    10  	"net/http"
    11  	"net/http/httptest"
    12  	"strings"
    13  	"testing"
    14  
    15  	"github.com/mssola/go-utils/security"
    16  )
    17  
    18  func TestCreateUserPage(t *testing.T) {
    19  	initTestDB()
    20  	defer closeTestDB()
    21  
    22  	req, err := http.NewRequest("GET", "/", nil)
    23  	if err != nil {
    24  		t.Fatalf("Expected to be nil: %v", err)
    25  	}
    26  	w := httptest.NewRecorder()
    27  	RootIndex(w, req)
    28  
    29  	if w.Code != 200 {
    30  		t.Fatalf("Got %v; Expected: %v", w.Code, 200)
    31  	}
    32  	if strings.Contains("<h1>Create user</h1>", w.Body.String()) {
    33  		t.Fatalf("Body should've contained '<h1>Create user</h1>'")
    34  	}
    35  }
    36  
    37  func TestLoginPage(t *testing.T) {
    38  	initTestDB()
    39  	defer closeTestDB()
    40  
    41  	password := security.PasswordSalt("1111")
    42  	createUser("user", password)
    43  
    44  	req, err := http.NewRequest("GET", "/", nil)
    45  	if err != nil {
    46  		t.Fatalf("Expected to be nil: %v", err)
    47  	}
    48  	w := httptest.NewRecorder()
    49  	RootIndex(w, req)
    50  
    51  	if w.Code != 200 {
    52  		t.Fatalf("Got %v, Expected: %v", w.Code, 200)
    53  	}
    54  	if strings.Contains("<h1>Login</h1>", w.Body.String()) {
    55  		t.Fatalf("Body should've contained '<h1>Login</h1>'")
    56  	}
    57  }
    58  
    59  func TestTopicsRedirect(t *testing.T) {
    60  	initTestDB()
    61  	defer closeTestDB()
    62  
    63  	password := security.PasswordSalt("1111")
    64  	createUser("user", password)
    65  
    66  	req, err := http.NewRequest("GET", "/", nil)
    67  	if err != nil {
    68  		t.Fatalf("Expected to be nil: %v", err)
    69  	}
    70  	w := httptest.NewRecorder()
    71  	login(w, req)
    72  	RootIndex(w, req)
    73  
    74  	if w.Code != 302 {
    75  		t.Fatalf("Got %v, Expected: %v", w.Code, 302)
    76  	}
    77  	if w.HeaderMap["Location"][0] != "/topics" {
    78  		t.Fatalf("Got %v, Expected: %v", w.HeaderMap["Location"][0], "/topics")
    79  	}
    80  }