k8s_audit: fix flaky windows test (#3940)

* k8s_audit: fix flaky windows test

On windows, immediately reusing a tcp port can lead to the observed
error. This commit randomizes the port number.

k8s-audit server failed: listen tcp 127.0.0.1:49234: bind: An attempt was made to access a socket in a way forbidden by its access permissions.

https://stackoverflow.com/questions/22549044/why-is-port-not-immediately-released-after-the-socket-closes

https://github.com/golang/go/issues/10527

* lint

* don't bother to ask for a free port, just give a different #
This commit is contained in:
mmetc
2025-10-03 10:26:41 +02:00
committed by GitHub
parent 5ea7ab451f
commit 19838930fa
@@ -1,6 +1,7 @@
package kubernetesauditacquisition
import (
"fmt"
"net/http/httptest"
"strings"
"testing"
@@ -109,7 +110,6 @@ func TestHandler(t *testing.T) {
ctx := t.Context()
tests := []struct {
name string
config string
expectedStatusCode int
body string
method string
@@ -117,10 +117,6 @@ func TestHandler(t *testing.T) {
}{
{
name: "valid_json",
config: `source: k8s-audit
listen_addr: 127.0.0.1
listen_port: 49234
webhook_path: /k8s-audit`,
method: "POST",
expectedStatusCode: 200,
body: `
@@ -216,10 +212,6 @@ webhook_path: /k8s-audit`,
},
{
name: "invalid_json",
config: `source: k8s-audit
listen_addr: 127.0.0.1
listen_port: 49234
webhook_path: /k8s-audit`,
expectedStatusCode: 500,
body: "invalid json",
method: "POST",
@@ -227,10 +219,6 @@ webhook_path: /k8s-audit`,
},
{
name: "invalid_method",
config: `source: k8s-audit
listen_addr: 127.0.0.1
listen_port: 49234
webhook_path: /k8s-audit`,
expectedStatusCode: 405,
method: "GET",
eventCount: 0,
@@ -239,7 +227,7 @@ webhook_path: /k8s-audit`,
subLogger := log.WithField("type", "k8s-audit")
for _, test := range tests {
for idx, test := range tests {
t.Run(test.name, func(t *testing.T) {
out := make(chan types.Event)
tb := &tomb.Tomb{}
@@ -257,9 +245,17 @@ webhook_path: /k8s-audit`,
})
f := KubernetesAuditSource{}
err := f.UnmarshalConfig([]byte(test.config))
port := 49234+idx
config := fmt.Sprintf(`source: k8s-audit
listen_addr: 127.0.0.1
listen_port: %d
webhook_path: /k8s-audit`, port)
err := f.UnmarshalConfig([]byte(config))
require.NoError(t, err)
err = f.Configure([]byte(test.config), subLogger, metrics.AcquisitionMetricsLevelNone)
err = f.Configure([]byte(config), subLogger, metrics.AcquisitionMetricsLevelNone)
require.NoError(t, err)