Skip to content

Commit

Permalink
add more test (easegress-io#632)
Browse files Browse the repository at this point in the history
* add more test

* add more test

* add more test for filters and register

* when meshcontroller is ready, then update their tests

* add more tests

* add more tests

* add more tests

* add more tests

* add more tests

* add more tests

* add more tests
  • Loading branch information
suchen-sci committed May 30, 2022
1 parent 21f959c commit 6cbfa18
Show file tree
Hide file tree
Showing 25 changed files with 949 additions and 34 deletions.
15 changes: 15 additions & 0 deletions pkg/cluster/layout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@
package cluster

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestLayout(t *testing.T) {
assert := assert.New(t)
l := Layout{}

if len(l.OtherLease("member-1")) == 0 {
Expand Down Expand Up @@ -67,4 +71,15 @@ func TestLayout(t *testing.T) {
if len(l.WasmDataPrefix("pipeline", "wasm")) == 0 {
t.Error("WasmDataPrefix empty")
}

statusObjectName := l.StatusObjectName("test-kind", "test-name")
assert.True(strings.Contains(statusObjectName, "test-kind"))
assert.True(strings.Contains(statusObjectName, "test-name"))

statusNamespaceFormat := l.StatusNamespaceFormat("test-ns", "test-name")
assert.True(strings.Contains(statusNamespaceFormat, "test-ns"))
assert.True(strings.Contains(statusNamespaceFormat, "test-name"))

assert.Equal(customDataPrefix, l.CustomDataPrefix())
assert.Equal(customDataKindPrefix, l.CustomDataKindPrefix())
}
3 changes: 3 additions & 0 deletions pkg/filters/fallback/fallback_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ mockBody: "mocked body"

fb := kind.CreateInstance(spec)
fb.Init()
assert.Equal("fallback", fb.Name())
assert.Equal(kind, fb.Kind())
assert.Equal(spec, fb.Spec())

ctx := context.New(tracing.NoopSpan)
resp, err := httpprot.NewResponse(nil)
Expand Down
48 changes: 48 additions & 0 deletions pkg/filters/filters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,22 @@ import (
"testing"

"github.com/megaease/easegress/pkg/util/yamltool"
"github.com/stretchr/testify/assert"
)

type mockSpec struct {
BaseSpec `yaml:",inline"`
Field string `yaml:"field" jsonschema:"required"`
}

var mockKind = &Kind{
Name: "Mock",
Description: "none",
Results: []string{},
DefaultSpec: func() Spec { return &mockSpec{} },
CreateInstance: func(spec Spec) Filter { return nil },
}

func TestSpecInherit(t *testing.T) {
type DerivedSpec struct {
BaseSpec `yaml:",inline"`
Expand Down Expand Up @@ -59,3 +73,37 @@ field1: abc
t.Error("wrong pipeline")
}
}

func TestNewSpec(t *testing.T) {
assert := assert.New(t)

_, err := NewSpec(nil, "pipelin1", func() {})
assert.NotNil(err, "marshal func should return err")

_, err = NewSpec(nil, "pipeline1", "invalid spec")
assert.NotNil(err, "unmarshal 'invalid spec' to MetaSpec should return err")

yamlStr := `
name: filter
kind: Filter
`
rawSpec := map[string]interface{}{}
yamltool.Unmarshal([]byte(yamlStr), &rawSpec)
_, err = NewSpec(nil, "pipeline1", rawSpec)
assert.NotNil(err, "kind Filter not exist")

// spec that work
kinds["Mock"] = mockKind
defer delete(kinds, "Mock")
yamlStr = `
name: filter
kind: Mock
field: 123
`
rawSpec = map[string]interface{}{}
yamltool.Unmarshal([]byte(yamlStr), &rawSpec)
spec, err := NewSpec(nil, "pipeline1", rawSpec)
assert.Nil(err)
assert.Nil(spec.Super())
assert.NotEmpty(spec.YAMLConfig())
}
31 changes: 30 additions & 1 deletion pkg/filters/headertojson/headertojson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"bytes"
"io"
"net/http"
"strings"
"testing"

json "github.com/goccy/go-json"
Expand Down Expand Up @@ -55,9 +56,19 @@ func TestHeaderToJSON(t *testing.T) {
spec := defaultFilterSpec(&Spec{})
h := kind.CreateInstance(spec)
h.Init()

assert.Equal(spec.Name(), h.Name())
assert.Equal(kind, h.Kind())
assert.Equal(spec, h.Spec())
assert.Nil(h.Status())

stdReq, err := http.NewRequest("", "/", nil)
assert.Nil(err)
req, err := httpprot.NewRequest(stdReq)
assert.Nil(err)
ctx := context.New(nil)
ctx.SetInputRequest(req)
assert.Equal("", h.Handle(ctx))

newh := kind.CreateInstance(spec)
newh.Inherit(h)
newh.Close()
Expand Down Expand Up @@ -165,4 +176,22 @@ func TestHandleHTTP(t *testing.T) {
}
}
}

{
// test http request with stream body
stdReq, err := http.NewRequest(http.MethodPost, "127.0.0.1", strings.NewReader("123"))
assert.Nil(err)
stdReq.Header.Add("x-username", "clientA")

req, err := httpprot.NewRequest(stdReq)
assert.Nil(err)
req.FetchPayload(-1)
assert.True(req.IsStream())

ctx := context.New(nil)
ctx.SetInputRequest(req)

ans := h2j.Handle(ctx)
assert.Equal(resultBodyReadErr, ans)
}
}
56 changes: 56 additions & 0 deletions pkg/filters/httpbuilder/extrafuncs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright (c) 2017, MegaEase
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package httpbuilder

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestToFloat64(t *testing.T) {
assert := assert.New(t)
assert.Equal(float64(1), toFloat64(int8(1)))
assert.Equal(float64(1), toFloat64(int16(1)))
assert.Equal(float64(1), toFloat64(int32(1)))
assert.Equal(float64(1), toFloat64(int64(1)))
assert.Equal(float64(1), toFloat64(int(1)))
assert.Equal(float64(1), toFloat64(uint8(1)))
assert.Equal(float64(1), toFloat64(uint16(1)))
assert.Equal(float64(1), toFloat64(uint32(1)))
assert.Equal(float64(1), toFloat64(uint64(1)))
assert.Equal(float64(1), toFloat64(uint(1)))
assert.Equal(float64(1), toFloat64(uintptr(1)))
assert.Equal(float64(1), toFloat64("1"))
assert.Panics(func() { toFloat64("s") })
assert.Panics(func() { toFloat64(func() {}) })
}

func TestExtraFuncs(t *testing.T) {
assert := assert.New(t)
assert.Equal(float64(123), extraFuncs["addf"].(func(a, b interface{}) float64)(120, 3))
assert.Equal(float64(117), extraFuncs["subf"].(func(a, b interface{}) float64)(120, 3))
assert.Equal(float64(360), extraFuncs["mulf"].(func(a, b interface{}) float64)(120, 3))
assert.Equal(float64(40), extraFuncs["divf"].(func(a, b interface{}) float64)(120, 3))
assert.Panics(func() { extraFuncs["divf"].(func(a, b interface{}) float64)(120, 0) })

assert.Equal("", extraFuncs["log"].(func(level, msg string) string)("debug", "debug"))
assert.Equal("", extraFuncs["log"].(func(level, msg string) string)("info", "info"))
assert.Equal("", extraFuncs["log"].(func(level, msg string) string)("warn", "warn"))
assert.Equal("", extraFuncs["log"].(func(level, msg string) string)("error", "error"))
}
6 changes: 1 addition & 5 deletions pkg/filters/httpbuilder/httpbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,6 @@ type (
Template string `yaml:"template" jsonschema:"required"`
}

builderData struct {
Requests map[string]*request
Responses map[string]*response
}

request struct {
*http.Request
rawBody []byte
Expand Down Expand Up @@ -161,6 +156,7 @@ func (r *response) JSONBody() (interface{}, error) {
func (r *response) YAMLBody() (interface{}, error) {
if r.parsedBody == nil {
var v interface{}
fmt.Printf("rawbody %v", string(r.rawBody))
err := yaml.Unmarshal(r.rawBody, &v)
if err != nil {
return nil, err
Expand Down
57 changes: 57 additions & 0 deletions pkg/filters/httpbuilder/httpbuilder_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright (c) 2017, MegaEase
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package httpbuilder

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestBuilderResponseBody(t *testing.T) {
assert := assert.New(t)
r := &response{
Response: nil,
rawBody: []byte("abc"),
}
assert.Equal([]byte("abc"), r.RawBody())
assert.Equal("abc", r.Body())
_, err := r.JSONBody()
assert.NotNil(err)

r = &response{
Response: nil,
rawBody: []byte("123"),
}
_, err = r.JSONBody()
assert.Nil(err)

r = &response{
Response: nil,
rawBody: []byte("{{{{{}"),
}
_, err = r.YAMLBody()
assert.NotNil(err)

r = &response{
Response: nil,
rawBody: []byte("123"),
}
_, err = r.YAMLBody()
assert.Nil(err)
}
83 changes: 83 additions & 0 deletions pkg/filters/httpbuilder/httprequestbuilder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ import (
"testing"

"github.com/megaease/easegress/pkg/context"
"github.com/megaease/easegress/pkg/filters"
"github.com/megaease/easegress/pkg/logger"
"github.com/megaease/easegress/pkg/protocols/httpprot"
"github.com/megaease/easegress/pkg/util/yamltool"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
)
Expand Down Expand Up @@ -321,4 +323,85 @@ field2: value2
assert.Nil(err)
assert.Equal("body value1 value2", string(data))
}

// use default method
yml = `template: |
url: http:https://www.facebook.com
`
{
spec := &HTTPRequestBuilderSpec{}
yaml.Unmarshal([]byte(yml), spec)
rb := getRequestBuilder(spec)
defer rb.Close()

ctx := context.New(nil)
ctx.UseNamespace("", "test")

res := rb.Handle(ctx)
assert.Empty(res)
testReq := ctx.GetRequest("test").(*httpprot.Request)
assert.Equal(http.MethodGet, testReq.Std().Method)
}

// use default url
yml = `template: |
method: delete
`
{
spec := &HTTPRequestBuilderSpec{}
yaml.Unmarshal([]byte(yml), spec)
rb := getRequestBuilder(spec)
defer rb.Close()

ctx := context.New(nil)
ctx.UseNamespace("", "test")

res := rb.Handle(ctx)
assert.Empty(res)
testReq := ctx.GetRequest("test").(*httpprot.Request)
assert.Equal(http.MethodDelete, testReq.Std().Method)
assert.Equal("/", testReq.Std().URL.String())
}

// build request failed
yml = `template: |
url: http:https://192.168.0.%31:8080/
`
{
spec := &HTTPRequestBuilderSpec{}
yaml.Unmarshal([]byte(yml), spec)
rb := getRequestBuilder(spec)
defer rb.Close()

ctx := context.New(nil)
ctx.UseNamespace("", "test")

res := rb.Handle(ctx)
assert.NotEmpty(res)
}
}

func TestHTTPRequestBuilder(t *testing.T) {
assert := assert.New(t)

assert.Equal(&HTTPRequestBuilderSpec{}, httpRequestBuilderKind.DefaultSpec())
yamlStr := `
name: requestBuilder
kind: HTTPRequestBuilder
template: |
method: Delete
`
rawSpec := map[string]interface{}{}
yamltool.Unmarshal([]byte(yamlStr), &rawSpec)
spec, err := filters.NewSpec(nil, "pipeline1", rawSpec)
assert.Nil(err)
requestBuilder := httpRequestBuilderKind.CreateInstance(spec).(*HTTPRequestBuilder)
assert.Equal("requestBuilder", requestBuilder.Name())
assert.Equal(httpRequestBuilderKind, requestBuilder.Kind())
assert.Equal(spec, requestBuilder.Spec())
requestBuilder.Init()

newRequestBuilder := httpRequestBuilderKind.CreateInstance(spec)
newRequestBuilder.Inherit(requestBuilder)
assert.Nil(newRequestBuilder.Status())
}
Loading

0 comments on commit 6cbfa18

Please sign in to comment.