Skip to content

Commit 557417c

Browse files
committed
Add unit tests to prevent IPv6 address formatting regression
Tests verify that newClient() correctly formats the gRPC address for: - IPv4 addresses: 192.168.1.10:50051 - IPv6 addresses: [2a05:d01c:ae4:ee06:1310::3]:50051 - IPv6 loopback: [::1]:50051 This prevents a repeat of the regression where fmt.Sprintf was used instead of net.JoinHostPort after code refactoring.
1 parent 65d9974 commit 557417c

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

controllers/medusa/common_test.go

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package medusa
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
"github.com/stretchr/testify/require"
9+
10+
cassdcapi "github.com/k8ssandra/cass-operator/apis/cassandra/v1beta1"
11+
"github.com/k8ssandra/k8ssandra-operator/pkg/medusa"
12+
corev1 "k8s.io/api/core/v1"
13+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
14+
)
15+
16+
// recordingClientFactory captures the address passed to NewClient for verification.
17+
type recordingClientFactory struct {
18+
lastAddress string
19+
}
20+
21+
func (f *recordingClientFactory) NewClient(address string) (medusa.Client, error) {
22+
f.lastAddress = address
23+
return nil, nil
24+
}
25+
26+
func (f *recordingClientFactory) NewClientWithTLS(address string, secret *corev1.Secret) (medusa.Client, error) {
27+
f.lastAddress = address
28+
return nil, nil
29+
}
30+
31+
func TestNewClientAddressFormatting(t *testing.T) {
32+
tests := []struct {
33+
name string
34+
podIP string
35+
expectedAddress string
36+
}{
37+
{
38+
name: "IPv4 address",
39+
podIP: "192.0.2.10", // RFC 5737 documentation range
40+
expectedAddress: "192.0.2.10:50051",
41+
},
42+
{
43+
name: "IPv6 address",
44+
podIP: "2001:db8:ae4:ee06:1310::3", // RFC 3849 documentation range
45+
expectedAddress: "[2001:db8:ae4:ee06:1310::3]:50051",
46+
},
47+
{
48+
name: "IPv6 loopback",
49+
podIP: "::1",
50+
expectedAddress: "[::1]:50051",
51+
},
52+
}
53+
54+
cassdc := &cassdcapi.CassandraDatacenter{
55+
ObjectMeta: metav1.ObjectMeta{
56+
Name: "dc1",
57+
Namespace: "test-ns",
58+
},
59+
}
60+
61+
for _, tt := range tests {
62+
t.Run(tt.name, func(t *testing.T) {
63+
factory := &recordingClientFactory{}
64+
pod := &corev1.Pod{
65+
ObjectMeta: metav1.ObjectMeta{
66+
Name: "test-pod",
67+
Namespace: "test-ns",
68+
},
69+
Status: corev1.PodStatus{
70+
PodIP: tt.podIP,
71+
},
72+
}
73+
74+
_, _ = newClient(context.Background(), nil, cassdc, pod, factory)
75+
76+
require.NotEmpty(t, factory.lastAddress)
77+
assert.Equal(t, tt.expectedAddress, factory.lastAddress)
78+
})
79+
}
80+
}

0 commit comments

Comments
 (0)