diff --git a/.gitignore b/.gitignore index 7b57f9e7..0e534a13 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,7 @@ # Visual Studio Code settings .vscode +# Goland settings +.idea/ + dist diff --git a/client/nginx.go b/client/nginx.go index 3d868c0e..7d16420a 100644 --- a/client/nginx.go +++ b/client/nginx.go @@ -588,6 +588,19 @@ func WithCheckAPI() Option { } } +// WithMaxAPIVersion sets the API version to the max API version. +func WithMaxAPIVersion() Option { + return func(o *NginxClient) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + version, err := o.GetMaxAPIVersion(ctx) + if err != nil { + return + } + o.apiVersion = version + } +} + // NewNginxClient creates a new NginxClient. func NewNginxClient(apiEndpoint string, opts ...Option) (*NginxClient, error) { c := &NginxClient{ diff --git a/client/nginx_test.go b/client/nginx_test.go index 655b3f82..290abeb2 100644 --- a/client/nginx_test.go +++ b/client/nginx_test.go @@ -601,6 +601,69 @@ func TestClientWithHTTPClient(t *testing.T) { } } +func TestClientWithMaxAPI(t *testing.T) { + t.Parallel() + tests := []struct { + name string + apiVersions string + expected int + }{ + { + name: "Test 1: API versions contains invalid version", + apiVersions: `[4, 5, 6, 7, 8, 9, 25]`, + expected: APIVersion, + }, + { + name: "Test 2: No API versions, default API Version is used", + apiVersions: ``, + expected: APIVersion, + }, + { + name: "Test 3: API version lower than default", + apiVersions: `[4, 5, 6, 7]`, + expected: 7, + }, + { + name: "Test 4: No API versions, default API version is used", + apiVersions: `[""]`, + expected: APIVersion, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // Test creating a new client with max API version + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.RequestURI == "/": + _, err := w.Write([]byte(tt.apiVersions)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + default: + _, err := w.Write([]byte(`{}`)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + } + })) + defer ts.Close() + + client, err := NewNginxClient(ts.URL, WithMaxAPIVersion()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if client == nil { + t.Fatalf("client is nil") + } + if client.apiVersion != tt.expected { + t.Fatalf("expected client.apiVersion to be %v, but got %v", tt.expected, client.apiVersion) + } + }) + } +} + func TestGetStats_NoStreamEndpoint(t *testing.T) { var writeLock sync.Mutex