github.com/astaxie/beego@v1.12.3/flash_test.go (about)

     1  // Copyright 2014 beego Author. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package beego
    16  
    17  import (
    18  	"net/http"
    19  	"net/http/httptest"
    20  	"strings"
    21  	"testing"
    22  )
    23  
    24  type TestFlashController struct {
    25  	Controller
    26  }
    27  
    28  func (t *TestFlashController) TestWriteFlash() {
    29  	flash := NewFlash()
    30  	flash.Notice("TestFlashString")
    31  	flash.Store(&t.Controller)
    32  	// we choose to serve json because we don't want to load a template html file
    33  	t.ServeJSON(true)
    34  }
    35  
    36  func TestFlashHeader(t *testing.T) {
    37  	// create fake GET request
    38  	r, _ := http.NewRequest("GET", "/", nil)
    39  	w := httptest.NewRecorder()
    40  
    41  	// setup the handler
    42  	handler := NewControllerRegister()
    43  	handler.Add("/", &TestFlashController{}, "get:TestWriteFlash")
    44  	handler.ServeHTTP(w, r)
    45  
    46  	// get the Set-Cookie value
    47  	sc := w.Header().Get("Set-Cookie")
    48  	// match for the expected header
    49  	res := strings.Contains(sc, "BEEGO_FLASH=%00notice%23BEEGOFLASH%23TestFlashString%00")
    50  	// validate the assertion
    51  	if !res {
    52  		t.Errorf("TestFlashHeader() unable to validate flash message")
    53  	}
    54  }