appsrv_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2019 Yunion
  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. package appsrv
  15. import (
  16. "context"
  17. "net/http"
  18. "testing"
  19. "time"
  20. "github.com/stretchr/testify/assert"
  21. "github.com/stretchr/testify/suite"
  22. )
  23. func TestSplitPath(t *testing.T) {
  24. cases := []struct {
  25. in string
  26. out int
  27. }{
  28. {in: "/v2.0/tokens/123", out: 3},
  29. {in: "/v2.0//tokens//123", out: 3},
  30. {in: "/", out: 0},
  31. {in: "/v2.0//123//", out: 2},
  32. }
  33. for _, p := range cases {
  34. ret := SplitPath(p.in)
  35. if len(ret) != p.out {
  36. t.Error("Split error for ", p.in, " out ", ret)
  37. }
  38. }
  39. }
  40. type ApplicationTestSuit struct {
  41. suite.Suite
  42. app *Application
  43. done chan<- struct{}
  44. }
  45. func (suite *ApplicationTestSuit) SetupTest() {
  46. suite.app = NewApplication("test", 4, 10, false)
  47. suite.app.AddHandler("GET", "/delay", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  48. time.Sleep(time.Second * 1)
  49. Send(w, "delay pong")
  50. })
  51. suite.app.AddHandler("GET", "/panic", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  52. panic("the handler is panic")
  53. })
  54. suite.app.AddHandler("GET", "/delaypanic", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  55. time.Sleep(time.Second * 1)
  56. panic("the handler is delay panic")
  57. })
  58. //suite.goServe()
  59. }
  60. func (suite *ApplicationTestSuit) goServe() {
  61. go func() {
  62. suite.app.ListenAndServe("0.0.0.0:44444")
  63. }()
  64. }
  65. func (suite *ApplicationTestSuit) TestHandler() {
  66. app := suite.app
  67. assert.True(suite.T(), assert.HTTPBodyContains(suite.T(), app.ServeHTTP, "GET", "/delay", nil, "delay pong"))
  68. assert.True(suite.T(), assert.HTTPBodyContains(suite.T(), app.ServeHTTP, "GET", "/panic", nil, "the handler is panic"))
  69. assert.True(suite.T(), assert.HTTPBodyContains(suite.T(), app.ServeHTTP, "GET", "/delaypanic", nil, "the handler is delay panic"))
  70. }
  71. func TestApplicationTestSuite(t *testing.T) {
  72. suite.Run(t, new(ApplicationTestSuit))
  73. }