Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing: move tests into black box scope #6605

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gateway/analytics_go_plugin_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package gateway
package gateway_test

import (
"net/http"
Expand Down
6 changes: 3 additions & 3 deletions gateway/api_definition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -871,7 +871,7 @@ func TestSyncAPISpecsDashboardSuccess(t *testing.T) {
t.Fatalf("want %q, got %q", want, got)
}
}
ts.Gw.handleRedisEvent(&msg, handled, wg.Done)
ts.Gw.HandleRedisEvent(&msg, handled, wg.Done)

ts.Gw.ReloadTestCase.TickOk(t)
// Wait for the reload to finish, then check it worked
Expand Down Expand Up @@ -1222,7 +1222,7 @@ func TestSyncAPISpecsDashboardJSONFailure(t *testing.T) {
t.Fatalf("want %q, got %q", want, got)
}
}
ts.Gw.handleRedisEvent(&msg, handled, wg.Done)
ts.Gw.HandleRedisEvent(&msg, handled, wg.Done)

ts.Gw.ReloadTestCase.TickOk(t)

Expand All @@ -1239,7 +1239,7 @@ func TestSyncAPISpecsDashboardJSONFailure(t *testing.T) {
var wg2 sync.WaitGroup
wg2.Add(1)
ts.Gw.ReloadTestCase.Reset()
ts.Gw.handleRedisEvent(&msg, handled, wg2.Done)
ts.Gw.HandleRedisEvent(&msg, handled, wg2.Done)

ts.Gw.ReloadTestCase.TickOk(t)
// Wait for the reload to finish, then check it worked
Expand Down
13 changes: 7 additions & 6 deletions gateway/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/TykTechnologies/tyk/apidef/oas"
"github.com/TykTechnologies/tyk/certs"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/ctx"
"github.com/TykTechnologies/tyk/internal/uuid"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/test"
Expand Down Expand Up @@ -963,7 +964,7 @@ func TestDisableKeyActionsByUserName(t *testing.T) {
ts := StartTest(conf)
defer ts.Close()

session := ts.testPrepareBasicAuth(false)
session := ts.TestPrepareBasicAuth(false)
userName := "defaultuser1"
res, _ := ts.Run(t, []test.TestCase{
{
Expand Down Expand Up @@ -1042,7 +1043,7 @@ func TestHashKeyHandlerLegacyWithHashFunc(t *testing.T) {
ts.Gw.SetConfig(globalConf)

// create session with legacy key format
session := ts.testPrepareBasicAuth(false)
session := ts.TestPrepareBasicAuth(false)

_, _ = ts.Run(t, []test.TestCase{
{
Expand Down Expand Up @@ -1207,7 +1208,7 @@ func (ts *Test) testHashKeyHandlerHelper(t *testing.T, expectedHashSize int) {

func (ts *Test) testHashFuncAndBAHelper(t *testing.T) {
t.Helper()
session := ts.testPrepareBasicAuth(false)
session := ts.TestPrepareBasicAuth(false)

_, _ = ts.Run(t, []test.TestCase{
{
Expand Down Expand Up @@ -1953,7 +1954,7 @@ func TestContextSession(t *testing.T) {
t.Fatal("expected ctxGetSession to return nil")
}

ctxSetSession(r,
ctx.SetSession(r,
&user.SessionState{},
false,
false)
Expand All @@ -1963,10 +1964,10 @@ func TestContextSession(t *testing.T) {
}
defer func() {
if r := recover(); r == nil {
t.Fatal("expected ctxSetSession of zero val to panic")
t.Fatal("expected ctx.SetSession of zero val to panic")
}
}()
ctxSetSession(r, nil, false, false)
ctx.SetSession(r, nil, false, false)
}

func TestRotateClientSecretHandler(t *testing.T) {
Expand Down
3 changes: 2 additions & 1 deletion gateway/auth_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"github.com/TykTechnologies/tyk/certs"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/internal/httputil"

"github.com/TykTechnologies/tyk/header"

Expand Down Expand Up @@ -221,7 +222,7 @@ func TestHashKeyFunctionChanged(t *testing.T) {
Code: http.StatusOK,
})

authHeader := map[string]string{"Authorization": genAuthHeader("user", "password")}
authHeader := map[string]string{"Authorization": httputil.AuthHeader("user", "password")}

testChangeHashFunc(t, authHeader, client, http.StatusUnauthorized)

Expand Down
3 changes: 1 addition & 2 deletions gateway/batch_requests_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,10 @@ import (
"sync/atomic"
"testing"

"github.com/TykTechnologies/tyk/certs"

"github.com/valyala/fasthttp"

"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/certs"
"github.com/TykTechnologies/tyk/test"
)

Expand Down
101 changes: 101 additions & 0 deletions gateway/blackbox_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package gateway_test

import (
"net/http"

"github.com/TykTechnologies/tyk/ctx"
"github.com/TykTechnologies/tyk/gateway"
)

// These are symbol shims from the gateway package to make life easier.
// It's all test symbols that have leaked into the package API.
type (
// Gateway is the service object.
Gateway = gateway.Gateway
ReverseProxy = gateway.ReverseProxy
APIDefinitionLoader = gateway.APIDefinitionLoader

// Middlewares used by tests explicitly
BaseMiddleware = gateway.BaseMiddleware
TransformMiddleware = gateway.TransformMiddleware
ResponseTransformMiddleware = gateway.ResponseTransformMiddleware
ResponseCacheMiddleware = gateway.ResponseCacheMiddleware
ResponseGoPluginMiddleware = gateway.ResponseGoPluginMiddleware
IPWhiteListMiddleware = gateway.IPWhiteListMiddleware
IPBlackListMiddleware = gateway.IPBlackListMiddleware
// Slight naming violation
MiddlewareContextVars = gateway.MiddlewareContextVars

// Tests leakage.
Test = gateway.Test
TestConfig = gateway.TestConfig
TestHttpResponse = gateway.TestHttpResponse
TraceHttpRequest = gateway.TraceHttpRequest

// Data model.
APISpec = gateway.APISpec
TransformSpec = gateway.TransformSpec
HostHealthReport = gateway.HostHealthReport
HostCheckCallBacks = gateway.HostCheckCallBacks
NotificationCommand = gateway.NotificationCommand
Notification = gateway.Notification
GraphQLRequest = gateway.GraphQLRequest
OASSchemaResponse = gateway.OASSchemaResponse
HeaderTransform = gateway.HeaderTransform
HeaderTransformOptions = gateway.HeaderTransformOptions
VersionMetas = gateway.VersionMetas
HeaderInjector = gateway.HeaderInjector
TransformHeaders = gateway.TransformHeaders

// Interfaces (data model).
IdExtractor = gateway.IdExtractor
WebHookHandler = gateway.WebHookHandler
HTTPDashboardHandler = gateway.HTTPDashboardHandler
BaseTykResponseHandler = gateway.BaseTykResponseHandler
)

// Constants are a coupling (data model).
const (
TestHttpAny = gateway.TestHttpAny
EH_LogHandler = gateway.EH_LogHandler
EH_WebHook = gateway.EH_WebHook

NoticeGroupReload = gateway.NoticeGroupReload
CachedResponseHeader = gateway.CachedResponseHeader
)

// Global functions are a coupling.
var (
BuildAPI = gateway.BuildAPI
BuildOASAPI = gateway.BuildOASAPI

StartTest = gateway.StartTest
InitTestMain = gateway.InitTestMain

CreateSession = gateway.CreateSession
CreateStandardSession = gateway.CreateStandardSession

GetTLSClient = gateway.GetTLSClient
MockOrgID = gateway.MockOrgID
UpdateAPIVersion = gateway.UpdateAPIVersion
TransformBody = gateway.TransformBody
TestReq = gateway.TestReq
)

// Alas, we have some internals.
var (
proxyOnErrorEnabled = true
keylessAuthEnabled = true
cacheEnabled = true

proxyOnErrorDisabled = false
keylessAuthDisabled = false
cacheDisabled = false
)

func ctxGetData(r *http.Request) map[string]interface{} {
if v := r.Context().Value(ctx.ContextData); v != nil {
return v.(map[string]interface{})
}
return nil
}
19 changes: 8 additions & 11 deletions gateway/cert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,16 @@
"github.com/stretchr/testify/assert"
"go.uber.org/mock/gomock"

"github.com/TykTechnologies/tyk/certs/mock"

"github.com/TykTechnologies/tyk/internal/crypto"

"github.com/TykTechnologies/tyk/header"
"github.com/TykTechnologies/tyk/storage"

"github.com/TykTechnologies/tyk/user"

"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/certs"
"github.com/TykTechnologies/tyk/certs/mock"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/header"
"github.com/TykTechnologies/tyk/internal/crypto"
"github.com/TykTechnologies/tyk/internal/httputil"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/test"
"github.com/TykTechnologies/tyk/user"
)

const (
Expand Down Expand Up @@ -1585,7 +1582,7 @@
assert.NoError(t, err)
defer ls.Close()

go listenProxyProto(ls)
go httputil.TestListenProxyProto(ls)

Check failure on line 1585 in gateway/cert_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

Error return value of `httputil.TestListenProxyProto` is not checked (errcheck)

certID, err := ts.Gw.CertificateManager.Add(combinedUpstreamCertPEM, "")
defer ts.Gw.CertificateManager.Delete(certID, "")
Expand Down Expand Up @@ -1641,7 +1638,7 @@
assert.NoError(t, err)
defer upstream.Close()

go listenProxyProto(upstream)
go httputil.TestListenProxyProto(upstream)

Check failure on line 1641 in gateway/cert_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

Error return value of `httputil.TestListenProxyProto` is not checked (errcheck)

// tyk
_, _, tykServerCombinedPEM, _ := crypto.GenServerCertificate()
Expand Down
6 changes: 2 additions & 4 deletions gateway/coprocess_bundle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ import (
"github.com/TykTechnologies/tyk/test"
)

var (
testBundlesPath = filepath.Join(testMiddlewarePath, "bundles")
)

func pkgPath() string {
_, filename, _, _ := runtime.Caller(0)
return filepath.Dir(filename) + "./.."
Expand Down Expand Up @@ -81,6 +77,8 @@ func TestBundleLoader(t *testing.T) {
})

t.Run("Existing bundle with auth check", func(t *testing.T) {
testBundlesPath := filepath.Join(ts.Gw.GetConfig().MiddlewarePath, "bundles")

spec := &APISpec{
APIDefinition: &apidef.APIDefinition{
CustomMiddlewareBundle: bundleID,
Expand Down
8 changes: 4 additions & 4 deletions gateway/dashboard_register.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,10 @@ func (gw *Gateway) reLogin() {
}

func (h *HTTPDashboardHandler) Init() error {
h.RegistrationEndpoint = h.Gw.buildDashboardConnStr("/register/node")
h.DeRegistrationEndpoint = h.Gw.buildDashboardConnStr("/system/node")
h.HeartBeatEndpoint = h.Gw.buildDashboardConnStr("/register/ping")
h.KeyQuotaTriggerEndpoint = h.Gw.buildDashboardConnStr("/system/key/quota_trigger")
h.RegistrationEndpoint = h.Gw.BuildDashboardConnStr("/register/node")
h.DeRegistrationEndpoint = h.Gw.BuildDashboardConnStr("/system/node")
h.HeartBeatEndpoint = h.Gw.BuildDashboardConnStr("/register/ping")
h.KeyQuotaTriggerEndpoint = h.Gw.BuildDashboardConnStr("/system/key/quota_trigger")

if h.Secret = h.Gw.GetConfig().NodeSecret; h.Secret == "" {
dashLog.Fatal("Node secret is not set, required for dashboard connection")
Expand Down
26 changes: 2 additions & 24 deletions gateway/dashboard_register_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package gateway
package gateway_test

import (
"testing"
Expand All @@ -24,29 +24,7 @@ func Test_BuildDashboardConnStr(t *testing.T) {
ts.Gw.SetConfig(cfg)
}()

connStr := ts.Gw.buildDashboardConnStr("/test")
connStr := ts.Gw.BuildDashboardConnStr("/test")

assert.Equal(t, connStr, "http://localhost/test")
}

func Test_DashboardLifecycle(t *testing.T) {
var handler HTTPDashboardHandler

handler = HTTPDashboardHandler{
heartBeatStopSentinel: HeartBeatStarted,
}
assert.False(t, handler.isHeartBeatStopped())

handler = HTTPDashboardHandler{
heartBeatStopSentinel: HeartBeatStopped,
}

assert.True(t, handler.isHeartBeatStopped())

handler = HTTPDashboardHandler{
heartBeatStopSentinel: HeartBeatStarted,
}

handler.StopBeating()
assert.True(t, handler.isHeartBeatStopped())
}
Loading
Loading