github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_unit_session_test.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  // SESSION测试
     8  package ghttp_test
     9  
    10  import (
    11  	"fmt"
    12  	"github.com/zhongdalu/gf/g"
    13  	"github.com/zhongdalu/gf/g/net/ghttp"
    14  	"github.com/zhongdalu/gf/g/test/gtest"
    15  	"testing"
    16  	"time"
    17  )
    18  
    19  func Test_Session(t *testing.T) {
    20  	p := ports.PopRand()
    21  	s := g.Server(p)
    22  	s.BindHandler("/set", func(r *ghttp.Request) {
    23  		r.Session.Set(r.Get("k"), r.Get("v"))
    24  	})
    25  	s.BindHandler("/get", func(r *ghttp.Request) {
    26  		r.Response.Write(r.Session.Get(r.Get("k")))
    27  	})
    28  	s.BindHandler("/remove", func(r *ghttp.Request) {
    29  		r.Session.Remove(r.Get("k"))
    30  	})
    31  	s.BindHandler("/clear", func(r *ghttp.Request) {
    32  		r.Session.Clear()
    33  	})
    34  	s.SetPort(p)
    35  	s.SetDumpRouteMap(false)
    36  	s.Start()
    37  	defer s.Shutdown()
    38  
    39  	// 等待启动完成
    40  	time.Sleep(time.Second)
    41  	gtest.Case(t, func() {
    42  		client := ghttp.NewClient()
    43  		client.SetBrowserMode(true)
    44  		client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
    45  		r1, e1 := client.Get("/set?k=key1&v=100")
    46  		if r1 != nil {
    47  			defer r1.Close()
    48  		}
    49  		gtest.Assert(e1, nil)
    50  		gtest.Assert(r1.ReadAllString(), "")
    51  
    52  		gtest.Assert(client.GetContent("/set?k=key2&v=200"), "")
    53  
    54  		gtest.Assert(client.GetContent("/get?k=key1"), "100")
    55  		gtest.Assert(client.GetContent("/get?k=key2"), "200")
    56  		gtest.Assert(client.GetContent("/get?k=key3"), "")
    57  		gtest.Assert(client.GetContent("/remove?k=key1"), "")
    58  		gtest.Assert(client.GetContent("/remove?k=key3"), "")
    59  		gtest.Assert(client.GetContent("/remove?k=key4"), "")
    60  		gtest.Assert(client.GetContent("/get?k=key1"), "")
    61  		gtest.Assert(client.GetContent("/get?k=key2"), "200")
    62  		gtest.Assert(client.GetContent("/clear"), "")
    63  		gtest.Assert(client.GetContent("/get?k=key2"), "")
    64  	})
    65  }