oceanbase
93 строки · 2.3 Кб
1/**
2* Copyright (c) 2021 OceanBase
3* OceanBase CE is licensed under Mulan PubL v2.
4* You can use this software according to the terms and conditions of the Mulan PubL v2.
5* You may obtain a copy of Mulan PubL v2 at:
6* http://license.coscl.org.cn/MulanPubL-2.0
7* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
8* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
9* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
10* See the Mulan PubL v2 for more details.
11*/
12
13package server14
15import (16"context"17"net/http"18"net/http/httptest"19"testing"20"time"21
22"github.com/gin-gonic/gin"23. "github.com/smartystreets/goconvey/convey"24)
25
26func TestCounter(t *testing.T) {27count := new(Counter)28Convey("counter after init", t, func() {29So(count.sessionCount, ShouldEqual, 0)30})31
32count.incr()33Convey("counter after incr", t, func() {34So(count.sessionCount, ShouldEqual, 1)35})36
37count.decr()38Convey("counter after decr", t, func() {39So(count.sessionCount, ShouldEqual, 0)40})41}
42
43func TestHttpServer(t *testing.T) {44server := &HttpServer{45Counter: new(Counter),46Router: gin.Default(),47Server: &http.Server{48Addr: ":0",49},50}51
52w := httptest.NewRecorder()53server.UseCounter()54server.Router.GET("/foo", fooHandler)55end := make(chan bool, 1)56handler := func(w http.ResponseWriter, r *http.Request) {57server.Router.ServeHTTP(w, r)58time.Sleep(time.Second)59}60req := httptest.NewRequest(http.MethodGet, "/foo", nil)61go func() {62handler(w, req)63end <- true64}()65
66time.Sleep(10 * time.Millisecond)67t.Run("handle a 1 second request", func(t *testing.T) {68Convey("session count should be 1", t, func() {69So(server.Counter.sessionCount, ShouldEqual, 1)70})71
72err := server.Shutdown(context.Background())73Convey("server shutdown should fail", t, func() {74So(err, ShouldNotBeNil)75So(err.Error(), ShouldContainSubstring, "server shutdown failed")76})77})78
79<-end80t.Run("handle request end", func(t *testing.T) {81Convey("session count should be 0", t, func() {82So(server.Counter.sessionCount, ShouldEqual, 0)83})84err := server.Shutdown(context.Background())85Convey("server shutdown should success", t, func() {86So(err, ShouldBeNil)87})88})89}
90
91func fooHandler(c *gin.Context) {92time.Sleep(time.Second)93}
94