Skip to content

Commit

Permalink
config: refactor test defaultConfig
Browse files Browse the repository at this point in the history
Make `defaultConfig` return configuration equal to one
created from default flags and modified by a helper function
for defining expected test case values.

Signed-off-by: Alexander Yastrebov <alexander.yastrebov@zalando.de>
  • Loading branch information
AlexanderYastrebov committed Apr 26, 2024
1 parent 429e8b5 commit fb66630
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 143 deletions.
200 changes: 57 additions & 143 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"time"

log "github.com/sirupsen/logrus"
"github.com/zalando/skipper/filters/openpolicyagent"
"github.com/zalando/skipper/net"
"github.com/zalando/skipper/proxy"
"gopkg.in/yaml.v2"
Expand Down Expand Up @@ -62,148 +61,46 @@ func TestEnvOverrides_SwarmRedisPassword(t *testing.T) {
}
}

func defaultConfig() *Config {
return &Config{
ConfigFile: "testdata/test.yaml",
Flags: nil,
Address: "localhost:8080",
StatusChecks: nil,
ExpectedBytesPerRequest: 50 * 1024,
SupportListener: ":9911",
MaxLoopbacks: 12,
DefaultHTTPStatus: 404,
MaxAuditBody: 1024,
MaxMatcherBufferSize: 2097152,
MetricsFlavour: commaListFlag("codahale", "prometheus"),
FilterPlugins: newPluginFlag(),
PredicatePlugins: newPluginFlag(),
DataclientPlugins: newPluginFlag(),
MultiPlugins: newPluginFlag(),
CompressEncodings: commaListFlag("gzip", "deflate", "br"),
OpenTracing: "noop",
OpenTracingInitialSpan: "ingress",
OpentracingLogFilterLifecycleEvents: true,
OpentracingLogStreamEvents: true,
MetricsListener: ":9911",
MetricsPrefix: "skipper.",
RuntimeMetrics: true,
HistogramMetricBuckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
ApplicationLogLevel: log.InfoLevel,
ApplicationLogLevelString: "INFO",
ApplicationLogPrefix: "[APP]",
EtcdPrefix: "/skipper",
EtcdTimeout: 2 * time.Second,
AppendFilters: &defaultFiltersFlags{},
PrependFilters: &defaultFiltersFlags{},
DisabledFilters: commaListFlag(),
CloneRoute: routeChangerConfig{},
EditRoute: routeChangerConfig{},
SourcePollTimeout: 3000,
KubernetesEastWestRangeDomains: commaListFlag(),
KubernetesHealthcheck: true,
KubernetesHTTPSRedirect: true,
KubernetesHTTPSRedirectCode: 308,
KubernetesPathModeString: "kubernetes-ingress",
KubernetesRedisServicePort: 6379,
KubernetesBackendTrafficAlgorithmString: "traffic-predicate",
KubernetesDefaultLoadBalancerAlgorithm: "roundRobin",
Oauth2TokeninfoTimeout: 2 * time.Second,
Oauth2TokenintrospectionTimeout: 2 * time.Second,
Oauth2TokeninfoSubjectKey: "uid",
Oauth2GrantTokeninfoKeys: commaListFlag(),
Oauth2TokenCookieName: "oauth2-grant",
Oauth2TokenCookieRemoveSubdomains: 1,
WebhookTimeout: 2 * time.Second,
OidcDistributedClaimsTimeout: 2 * time.Second,
OIDCCookieValidity: time.Hour,
CredentialPaths: commaListFlag(),
CredentialsUpdateInterval: 10 * time.Minute,
ApiUsageMonitoringClientKeys: "sub",
ApiUsageMonitoringRealmsTrackingPattern: "services",
WaitForHealthcheckInterval: 45 * time.Second,
IdleConnsPerHost: 64,
CloseIdleConnsPeriod: 20 * time.Second,
BackendFlushInterval: 20 * time.Millisecond,
ReadTimeoutServer: 5 * time.Minute,
ReadHeaderTimeoutServer: 1 * time.Minute,
WriteTimeoutServer: 1 * time.Minute,
IdleTimeoutServer: 1 * time.Minute,
MaxHeaderBytes: 1048576,
TimeoutBackend: 1 * time.Minute,
KeepaliveBackend: 30 * time.Second,
EnableDualstackBackend: true,
TlsHandshakeTimeoutBackend: 1 * time.Minute,
ResponseHeaderTimeoutBackend: 1 * time.Minute,
ExpectContinueTimeoutBackend: 30 * time.Second,
ServeMethodMetric: true,
ServeStatusCodeMetric: true,
SwarmRedisURLs: commaListFlag(),
SwarmRedisPassword: "set_from_file",
SwarmRedisDialTimeout: 25 * time.Millisecond,
SwarmRedisReadTimeout: 25 * time.Millisecond,
SwarmRedisWriteTimeout: 25 * time.Millisecond,
SwarmRedisPoolTimeout: 25 * time.Millisecond,
SwarmRedisMinConns: 100,
SwarmRedisMaxConns: 100,
SwarmKubernetesNamespace: "kube-system",
SwarmKubernetesLabelSelectorKey: "application",
SwarmKubernetesLabelSelectorValue: "skipper-ingress",
SwarmPort: 9990,
SwarmMaxMessageBuffer: 4194304,
SwarmLeaveTimeout: 5 * time.Second,
TLSMinVersion: defaultMinTLSVersion,
RoutesURLs: commaListFlag(),
ForwardedHeadersList: commaListFlag(),
ForwardedHeadersExcludeCIDRList: commaListFlag(),
ClusterRatelimitMaxGroupShards: 1,
RefusePayload: multiFlag{"foo", "bar", "baz"},
ValidateQuery: true,
ValidateQueryLog: true,
LuaModules: commaListFlag(),
LuaSources: commaListFlag(),
OpenPolicyAgentCleanerInterval: openpolicyagent.DefaultCleanIdlePeriod,
OpenPolicyAgentStartupTimeout: 30 * time.Second,
OpenPolicyAgentMaxRequestBodySize: openpolicyagent.DefaultMaxRequestBodySize,
OpenPolicyAgentMaxMemoryBodyParsing: openpolicyagent.DefaultMaxMemoryBodyParsing,
func defaultConfig(with func(*Config)) *Config {
cfg := NewConfig()
err := cfg.ParseArgs("skipper-test", nil)
if err != nil {
panic(err)
}
}

func defaultConfigWithoutNil() *Config {
cfg := defaultConfig()
cfg.StatusChecks = newListFlag("", "")
with(cfg)
return cfg
}

func TestToOptions(t *testing.T) {
c := defaultConfigWithoutNil()
c := defaultConfig(func(c *Config) {
// ProxyFlags
c.Insecure = true // 1
c.ProxyPreserveHost = true // 4
c.RemoveHopHeaders = true // 16
c.RfcPatchPath = true // 32

// ProxyFlags
c.Insecure = true // 1
c.ProxyPreserveHost = true // 4
c.RemoveHopHeaders = true // 16
c.RfcPatchPath = true // 32

// config
c.EtcdUrls = "127.0.0.1:5555"
c.WhitelistedHealthCheckCIDR = "127.0.0.0/8,10.0.0.0/8"
c.ForwardedHeadersList = commaListFlag("X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Method,X-Forwarded-Uri,X-Forwarded-Port=,X-Forwarded-Proto=http")
c.ForwardedHeadersList.Set("X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Method,X-Forwarded-Uri,X-Forwarded-Port=,X-Forwarded-Proto=http")
c.HostPatch = net.HostPatch{
ToLower: true,
RemoteTrailingDot: true,
}
c.RefusePayload = append(c.RefusePayload, "refuse")
c.ValidateQuery = true
c.ValidateQueryLog = true
// config
c.EtcdUrls = "127.0.0.1:5555"
c.WhitelistedHealthCheckCIDR = "127.0.0.0/8,10.0.0.0/8"
c.ForwardedHeadersList = commaListFlag("X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Method,X-Forwarded-Uri,X-Forwarded-Port=,X-Forwarded-Proto=http")
c.ForwardedHeadersList.Set("X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Method,X-Forwarded-Uri,X-Forwarded-Port=,X-Forwarded-Proto=http")
c.HostPatch = net.HostPatch{
ToLower: true,
RemoteTrailingDot: true,
}
c.RefusePayload = append(c.RefusePayload, "refuse")
c.ValidateQuery = true
c.ValidateQueryLog = true

c.CloneRoute = routeChangerConfig{}
if err := c.CloneRoute.Set("/foo/bar/"); err != nil {
t.Fatalf("Failed to set: %v", err)
}
c.EditRoute = routeChangerConfig{}
if err := c.EditRoute.Set("/foo/bar/"); err != nil {
t.Fatalf("Failed to set: %v", err)
}
c.CloneRoute = routeChangerConfig{}
if err := c.CloneRoute.Set("/foo/bar/"); err != nil {
t.Fatalf("Failed to set: %v", err)
}
c.EditRoute = routeChangerConfig{}
if err := c.EditRoute.Set("/foo/bar/"); err != nil {
t.Fatalf("Failed to set: %v", err)
}
})

if err := validate(c); err != nil {
t.Fatalf("Failed to validate config: %v", err)
Expand Down Expand Up @@ -322,22 +219,39 @@ func Test_NewConfigWithArgs(t *testing.T) {
wantErr: true,
},
{
name: "test only valid flag overwrite yaml file",
args: []string{"skipper", "-config-file=testdata/test.yaml", "-address=localhost:8080", "-refuse-payload=baz"},
want: defaultConfig(),
wantErr: false,
name: "test only valid flag overwrite yaml file",
args: []string{"skipper", "-config-file=testdata/test.yaml", "-address=localhost:8080", "-refuse-payload=baz"},
want: defaultConfig(func(c *Config) {
c.ConfigFile = "testdata/test.yaml"
c.Address = "localhost:8080"
c.MaxLoopbacks = 12
c.EtcdTimeout = 2 * time.Second
c.StatusChecks = &listFlag{
sep: ",",
allowed: map[string]bool{},
value: "http://foo.test/bar,http://baz.test/qux",
values: []string{"http://foo.test/bar", "http://baz.test/qux"},
}
c.SwarmRedisPassword = "set_from_file"
c.RefusePayload = multiFlag{"foo", "bar", "baz"}
}),
},
} {
t.Run(tt.name, func(t *testing.T) {
cfg := NewConfig()
err := cfg.ParseArgs(tt.args[0], tt.args[1:])

if (err != nil) != tt.wantErr {
t.Errorf("config.NewConfig() error = %v, wantErr %v", err, tt.wantErr)
t.Fatalf("config.NewConfig() error: %v, wantErr: %v", err, tt.wantErr)
}

if !tt.wantErr {
if cmp.Equal(cfg, tt.want, cmp.AllowUnexported(listFlag{}, pluginFlag{}, defaultFiltersFlags{}, mapFlags{}), cmpopts.IgnoreUnexported(Config{}), cmpopts.IgnoreFields(Config{}, "Flags")) == false {
t.Errorf("config.NewConfig() got vs. want:\n%v", cmp.Diff(cfg, tt.want, cmp.AllowUnexported(listFlag{}, pluginFlag{}, defaultFiltersFlags{}, mapFlags{}), cmpopts.IgnoreUnexported(Config{}), cmpopts.IgnoreFields(Config{}, "Flags")))
d := cmp.Diff(cfg, tt.want,
cmp.AllowUnexported(listFlag{}, pluginFlag{}, defaultFiltersFlags{}, mapFlags{}),
cmpopts.IgnoreUnexported(Config{}), cmpopts.IgnoreFields(Config{}, "Flags"),
)
if d != "" {
t.Errorf("config.NewConfig() want vs got:\n%s", d)
}
}
})
Expand Down
2 changes: 2 additions & 0 deletions config/testdata/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ address: localhost:9090
max-loopbacks: 12
etcd-timeout: 2s
status-checks:
- http://foo.test/bar
- http://baz.test/qux
swarm-redis-password: set_from_file
refuse-payload:
- foo
Expand Down

0 comments on commit fb66630

Please sign in to comment.