From fc2839061836192211aaf6c3874056b63488e822 Mon Sep 17 00:00:00 2001
From: Roman Khavronenko <roman@victoriametrics.com>
Date: Tue, 30 Apr 2024 10:22:17 +0200
Subject: [PATCH] app/vmauth: add test for LeastLoaded balance policy (#6144)

Check if least-loaded works correctly.
related to
https://github.com/VictoriaMetrics/VictoriaMetrics/issues/6136

Signed-off-by: hagen1778 <roman@victoriametrics.com>
(cherry picked from commit e2590b339d68fdb1a07b8e906ff33cc380d2e464)
---
 app/vmauth/auth_config_test.go | 64 ++++++++++++++++++++++++++++++++++
 1 file changed, 64 insertions(+)

diff --git a/app/vmauth/auth_config_test.go b/app/vmauth/auth_config_test.go
index b7f8eea4f1..ca5aca2eab 100644
--- a/app/vmauth/auth_config_test.go
+++ b/app/vmauth/auth_config_test.go
@@ -685,6 +685,70 @@ func isSetBool(boolP *bool, expectedValue bool) bool {
 	return *boolP == expectedValue
 }
 
+func TestGetLeastLoadedBackendURL(t *testing.T) {
+	up := mustParseURLs([]string{
+		"http://node1:343",
+		"http://node2:343",
+		"http://node3:343",
+	})
+	up.loadBalancingPolicy = "least_loaded"
+
+	fn := func(ns ...int) {
+		t.Helper()
+		bus := up.bus.Load()
+		pbus := *bus
+		for i, b := range pbus {
+			got := int(b.concurrentRequests.Load())
+			exp := ns[i]
+			if got != exp {
+				t.Fatalf("expected %q to have %d concurrent requests; got %d instead", b.url, exp, got)
+			}
+		}
+	}
+
+	up.getBackendURL()
+	fn(0, 1, 0)
+	up.getBackendURL()
+	fn(0, 1, 1)
+	up.getBackendURL()
+	fn(1, 1, 1)
+
+	up.getBackendURL()
+	up.getBackendURL()
+	fn(1, 2, 2)
+
+	bus := up.bus.Load()
+	pbus := *bus
+	pbus[0].concurrentRequests.Add(2)
+	pbus[2].concurrentRequests.Add(5)
+	fn(3, 2, 7)
+
+	up.getBackendURL()
+	fn(3, 3, 7)
+
+	up.getBackendURL()
+	fn(3, 4, 7)
+
+	up.getBackendURL()
+	fn(4, 4, 7)
+
+	up.getBackendURL()
+	fn(5, 4, 7)
+
+	up.getBackendURL()
+	fn(5, 5, 7)
+
+	up.getBackendURL()
+	fn(6, 5, 7)
+
+	up.getBackendURL()
+	fn(6, 6, 7)
+
+	up.getBackendURL()
+	up.getBackendURL()
+	fn(7, 7, 7)
+}
+
 func getRegexs(paths []string) []*Regex {
 	var sps []*Regex
 	for _, path := range paths {