Skip to content

Commit

Permalink
apiutil, audit, autoscaling, cache: testify the tests (#5061)
Browse files Browse the repository at this point in the history
ref #4813

Testify the pkg/apiutil, pkg/audit, pkg/autoscaling, pkg/cache tests.

Signed-off-by: JmPotato <[email protected]>

Co-authored-by: ShuNing <[email protected]>
  • Loading branch information
JmPotato and nolouch authored May 30, 2022
1 parent f3cefe1 commit 6c9f8f6
Show file tree
Hide file tree
Showing 6 changed files with 244 additions and 284 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ require (
github.com/sasha-s/go-deadlock v0.2.0
github.com/spf13/cobra v1.0.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.7.0
github.com/swaggo/http-swagger v0.0.0-20200308142732-58ac5e232fba
github.com/swaggo/swag v1.6.6-0.20200529100950-7c765ddd0476
github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965
Expand Down
32 changes: 11 additions & 21 deletions pkg/apiutil/apiutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,11 @@ import (
"net/http/httptest"
"testing"

. "github.com/pingcap/check"
"github.com/stretchr/testify/require"
"github.com/unrolled/render"
)

func Test(t *testing.T) {
TestingT(t)
}

var _ = Suite(&testUtilSuite{})

type testUtilSuite struct{}

func (s *testUtilSuite) TestJsonRespondErrorOk(c *C) {
func TestJsonRespondErrorOk(t *testing.T) {
rd := render.New(render.Options{
IndentJSON: true,
})
Expand All @@ -41,36 +33,34 @@ func (s *testUtilSuite) TestJsonRespondErrorOk(c *C) {
var input map[string]string
output := map[string]string{"zone": "cn", "host": "local"}
err := ReadJSONRespondError(rd, response, body, &input)
c.Assert(err, IsNil)
c.Assert(input["zone"], Equals, output["zone"])
c.Assert(input["host"], Equals, output["host"])
require.NoError(t, err)
require.Equal(t, output["zone"], input["zone"])
require.Equal(t, output["host"], input["host"])
result := response.Result()
defer result.Body.Close()
c.Assert(result.StatusCode, Equals, 200)
require.Equal(t, 200, result.StatusCode)
}

func (s *testUtilSuite) TestJsonRespondErrorBadInput(c *C) {
func TestJsonRespondErrorBadInput(t *testing.T) {
rd := render.New(render.Options{
IndentJSON: true,
})
response := httptest.NewRecorder()
body := io.NopCloser(bytes.NewBufferString("{\"zone\":\"cn\", \"host\":\"local\"}"))
var input []string
err := ReadJSONRespondError(rd, response, body, &input)
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "json: cannot unmarshal object into Go value of type []string")
require.EqualError(t, err, "json: cannot unmarshal object into Go value of type []string")
result := response.Result()
defer result.Body.Close()
c.Assert(result.StatusCode, Equals, 400)
require.Equal(t, 400, result.StatusCode)

{
body := io.NopCloser(bytes.NewBufferString("{\"zone\":\"cn\","))
var input []string
err := ReadJSONRespondError(rd, response, body, &input)
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "unexpected end of JSON input")
require.EqualError(t, err, "unexpected end of JSON input")
result := response.Result()
defer result.Body.Close()
c.Assert(result.StatusCode, Equals, 400)
require.Equal(t, 400, result.StatusCode)
}
}
50 changes: 22 additions & 28 deletions pkg/audit/audit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,32 +24,22 @@ import (
"testing"
"time"

. "github.com/pingcap/check"
"github.com/pingcap/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/stretchr/testify/require"
"github.com/tikv/pd/pkg/requestutil"
)

func Test(t *testing.T) {
TestingT(t)
}

var _ = Suite(&testAuditSuite{})

type testAuditSuite struct {
}

func (s *testAuditSuite) TestLabelMatcher(c *C) {
func TestLabelMatcher(t *testing.T) {
matcher := &LabelMatcher{"testSuccess"}
labels1 := &BackendLabels{Labels: []string{"testFail", "testSuccess"}}
c.Assert(matcher.Match(labels1), Equals, true)

require.True(t, matcher.Match(labels1))
labels2 := &BackendLabels{Labels: []string{"testFail"}}
c.Assert(matcher.Match(labels2), Equals, false)
require.False(t, matcher.Match(labels2))
}

func (s *testAuditSuite) TestPrometheusHistogramBackend(c *C) {
func TestPrometheusHistogramBackend(t *testing.T) {
serviceAuditHistogramTest := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "pd",
Expand All @@ -70,44 +60,48 @@ func (s *testAuditSuite) TestPrometheusHistogramBackend(c *C) {
info.ServiceLabel = "test"
info.Component = "user1"
req = req.WithContext(requestutil.WithRequestInfo(req.Context(), info))
c.Assert(backend.ProcessHTTPRequest(req), Equals, false)
require.False(t, backend.ProcessHTTPRequest(req))

endTime := time.Now().Unix() + 20
req = req.WithContext(requestutil.WithEndTime(req.Context(), endTime))

c.Assert(backend.ProcessHTTPRequest(req), Equals, true)
c.Assert(backend.ProcessHTTPRequest(req), Equals, true)
require.True(t, backend.ProcessHTTPRequest(req))
require.True(t, backend.ProcessHTTPRequest(req))

info.Component = "user2"
req = req.WithContext(requestutil.WithRequestInfo(req.Context(), info))
c.Assert(backend.ProcessHTTPRequest(req), Equals, true)
require.True(t, backend.ProcessHTTPRequest(req))

// For test, sleep time needs longer than the push interval
time.Sleep(1 * time.Second)
req, _ = http.NewRequest("GET", ts.URL, nil)
resp, err := http.DefaultClient.Do(req)
c.Assert(err, IsNil)
require.NoError(t, err)
defer resp.Body.Close()
content, _ := io.ReadAll(resp.Body)
output := string(content)
c.Assert(strings.Contains(output, "pd_service_audit_handling_seconds_test_count{component=\"user1\",method=\"HTTP\",service=\"test\"} 2"), Equals, true)
c.Assert(strings.Contains(output, "pd_service_audit_handling_seconds_test_count{component=\"user2\",method=\"HTTP\",service=\"test\"} 1"), Equals, true)
require.Contains(t, output, "pd_service_audit_handling_seconds_test_count{component=\"user1\",method=\"HTTP\",service=\"test\"} 2")
require.Contains(t, output, "pd_service_audit_handling_seconds_test_count{component=\"user2\",method=\"HTTP\",service=\"test\"} 1")
}

func (s *testAuditSuite) TestLocalLogBackendUsingFile(c *C) {
func TestLocalLogBackendUsingFile(t *testing.T) {
backend := NewLocalLogBackend(true)
fname := initLog()
defer os.Remove(fname)
req, _ := http.NewRequest("GET", "http://127.0.0.1:2379/test?test=test", strings.NewReader("testBody"))
c.Assert(backend.ProcessHTTPRequest(req), Equals, false)
require.False(t, backend.ProcessHTTPRequest(req))
info := requestutil.GetRequestInfo(req)
req = req.WithContext(requestutil.WithRequestInfo(req.Context(), info))
c.Assert(backend.ProcessHTTPRequest(req), Equals, true)
require.True(t, backend.ProcessHTTPRequest(req))
b, _ := os.ReadFile(fname)
output := strings.SplitN(string(b), "]", 4)
c.Assert(output[3], Equals, fmt.Sprintf(" [\"Audit Log\"] [service-info=\"{ServiceLabel:, Method:HTTP/1.1/GET:/test, Component:anonymous, IP:, "+
"StartTime:%s, URLParam:{\\\"test\\\":[\\\"test\\\"]}, BodyParam:testBody}\"]\n",
time.Unix(info.StartTimeStamp, 0).String()))
require.Equal(
t,
fmt.Sprintf(" [\"Audit Log\"] [service-info=\"{ServiceLabel:, Method:HTTP/1.1/GET:/test, Component:anonymous, IP:, "+
"StartTime:%s, URLParam:{\\\"test\\\":[\\\"test\\\"]}, BodyParam:testBody}\"]\n",
time.Unix(info.StartTimeStamp, 0).String()),
output[3],
)
}

func BenchmarkLocalLogAuditUsingTerminal(b *testing.B) {
Expand Down
Loading

0 comments on commit 6c9f8f6

Please sign in to comment.