github.com/dbernstein1/tyk@v2.9.0-beta9-dl-apic+incompatible/gateway/mw_virtual_endpoint_test.go (about) 1 package gateway 2 3 import ( 4 "encoding/base64" 5 "net/http" 6 "testing" 7 8 "github.com/TykTechnologies/tyk/apidef" 9 "github.com/TykTechnologies/tyk/test" 10 ) 11 12 const virtTestJS = ` 13 function testVirtData(request, session, config) { 14 var resp = { 15 Body: "foobar", 16 Headers: { 17 "data-foo": config.config_data.foo, 18 "data-bar-y": config.config_data.bar.y.toString() 19 }, 20 Code: 202 21 } 22 return TykJsResponse(resp, session.meta_data) 23 } 24 ` 25 26 func testPrepareVirtualEndpoint(js string, method string, path string, proxyOnError bool) { 27 BuildAndLoadAPI(func(spec *APISpec) { 28 spec.Proxy.ListenPath = "/" 29 30 virtualMeta := apidef.VirtualMeta{ 31 ResponseFunctionName: "testVirtData", 32 FunctionSourceType: "blob", 33 FunctionSourceURI: base64.StdEncoding.EncodeToString([]byte(js)), 34 Path: path, 35 Method: method, 36 ProxyOnError: proxyOnError, 37 } 38 v := spec.VersionData.Versions["v1"] 39 v.UseExtendedPaths = true 40 v.ExtendedPaths = apidef.ExtendedPathsSet{ 41 Virtual: []apidef.VirtualMeta{virtualMeta}, 42 } 43 spec.VersionData.Versions["v1"] = v 44 45 spec.ConfigData = map[string]interface{}{ 46 "foo": "x", 47 "bar": map[string]interface{}{"y": 3}, 48 } 49 50 // Address https://github.com/TykTechnologies/tyk/issues/1356 51 // VP should work with cache enabled 52 spec.CacheOptions = apidef.CacheOptions{ 53 EnableCache: true, 54 CacheTimeout: 60, 55 CacheAllSafeRequests: true, 56 } 57 }) 58 } 59 60 func TestVirtualEndpoint(t *testing.T) { 61 ts := StartTest() 62 defer ts.Close() 63 64 testPrepareVirtualEndpoint(virtTestJS, "GET", "/virt", true) 65 66 ts.Run(t, test.TestCase{ 67 Path: "/virt", 68 Code: 202, 69 BodyMatch: "foobar", 70 HeadersMatch: map[string]string{ 71 "data-foo": "x", 72 "data-bar-y": "3", 73 }, 74 }) 75 } 76 77 func TestVirtualEndpoint500(t *testing.T) { 78 ts := StartTest() 79 defer ts.Close() 80 81 testPrepareVirtualEndpoint("abc", "GET", "/abc", false) 82 83 ts.Run(t, test.TestCase{ 84 Path: "/abc", 85 Code: http.StatusInternalServerError, 86 }) 87 } 88 89 func BenchmarkVirtualEndpoint(b *testing.B) { 90 b.ReportAllocs() 91 92 ts := StartTest() 93 defer ts.Close() 94 95 testPrepareVirtualEndpoint(virtTestJS, "GET", "/virt", true) 96 97 for i := 0; i < b.N; i++ { 98 ts.Run(b, test.TestCase{ 99 Path: "/virt", 100 Code: 202, 101 BodyMatch: "foobar", 102 HeadersMatch: map[string]string{ 103 "data-foo": "x", 104 "data-bar-y": "3", 105 }, 106 }) 107 } 108 }