github.com/Tyktechnologies/tyk@v2.9.5+incompatible/gateway/mw_transform_jq_test.go (about)

     1  // +build jq
     2  
     3  package gateway
     4  
     5  import (
     6  	"testing"
     7  
     8  	"github.com/TykTechnologies/tyk/apidef"
     9  	"github.com/TykTechnologies/tyk/test"
    10  )
    11  
    12  func testPrepareJQMiddleware() {
    13  	BuildAndLoadAPI(func(spec *APISpec) {
    14  		spec.Proxy.ListenPath = "/"
    15  		spec.EnableContextVars = true
    16  		UpdateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
    17  			v.UseExtendedPaths = true
    18  			v.ExtendedPaths.TransformJQ = []apidef.TransformJQMeta{{
    19  				Path:   "/jq",
    20  				Method: "POST",
    21  				Filter: `{"body": (.body + {"TRANSFORMED-REQUEST-BY-JQ": true, path: ._tyk_context.path, user_agent: ._tyk_context.headers_User_Agent}), "rewrite_headers": {"X-added-rewrite-headers": .body.foo}, "tyk_context": { "foo-val": .body.foo}}`,
    22  			}}
    23  		})
    24  	})
    25  }
    26  
    27  func TestJQMiddleware(t *testing.T) {
    28  	ts := StartTest()
    29  	defer ts.Close()
    30  
    31  	testPrepareJQMiddleware()
    32  
    33  	bodyContextVar := `\"path\":\"/jq\"`
    34  	headersBodyVar := `"X-Added-Rewrite-Headers":"bar"`
    35  
    36  	ts.Run(t, []test.TestCase{
    37  		{Path: "/jq", Method: "POST", Data: `{"foo": "bar"}`, Code: 200, BodyMatch: bodyContextVar},
    38  		{Path: "/jq", Method: "POST", Data: `{"foo": "bar"}`, Code: 200, BodyMatch: headersBodyVar},
    39  		{Path: "/jq", Method: "POST", Data: `wrong json`, Code: 415},
    40  	}...)
    41  }
    42  
    43  func BenchmarkJQMiddleware(b *testing.B) {
    44  	b.ReportAllocs()
    45  
    46  	ts := StartTest()
    47  	defer ts.Close()
    48  
    49  	testPrepareJQMiddleware()
    50  
    51  	bodyContextVar := `\"path\":\"/jq\"`
    52  	headersBodyVar := `"X-Added-Rewrite-Headers":"bar"`
    53  
    54  	for i := 0; i < b.N; i++ {
    55  		ts.Run(b, []test.TestCase{
    56  			{Path: "/jq", Method: "POST", Data: `{"foo": "bar"}`, Code: 200, BodyMatch: bodyContextVar},
    57  			{Path: "/jq", Method: "POST", Data: `{"foo": "bar"}`, Code: 200, BodyMatch: headersBodyVar},
    58  			{Path: "/jq", Method: "POST", Data: `wrong json`, Code: 415},
    59  		}...)
    60  	}
    61  }